我已经尝试了两天将 .htaccess 转换为 nginx,重写原始文件如下所示:
# Turn on URL rewriting
RewriteEngine On
RewriteBase //
# Protect hidden files from being viewed
<Files .*>
Order Deny,Allow
Deny From All
</Files>
# Protect application and system files from being viewed
RewriteRule ^(?:application|modules|system)\b.* index.php/$0 [L]
# List of files in subdirectories will not be displayed in the browser
Options -Indexes
# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
AddDefaultCharset utf-8
AddCharset UTF-8 .htm .html .txt
AddType "text/html; charset=UTF-8" .htm .html .txt
AddType "text/css; charset=UTF-8" .css
AddType "text/javascript; charset=UTF-8" .js
# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT]
我想出了这个:
# nginx configuration
charset utf-8;
autoindex off;
location /application {
rewrite ^/(?:application|modules|system)\b.* /index.php/$0 break;
}
location /modules {
rewrite ^/(?:application|modules|system)\b.* /index.php/$0 break;
}
location /system {
rewrite ^/(?:application|modules|system)\b.* /index.php/$0 break;
}
location / {
if (!-e $request_filename){
rewrite ^(.*)$ /index.php/$0;
}
}
location ~ \.* {
deny all;
}
但是当我重新启动 nginx 时我得到:
[emerg] unknown "0" variable
nginx: configuration file /etc/nginx/nginx.conf test failed
我不明白这是为什么。有人能帮我解决这个问题吗?
答案1
nginx 没有$0
在 Apache 中用于整个正则表达式模式匹配的变量。
在 nginx 中,您可以使用 获取等效字符串$request_uri
。
因此,您应该使用如下配置:
charset utf-8;
autoindex off;
location ~ /\.* {
deny all;
}
location ~ /(?:application|modules|system) {
return 301 /index.php$request_uri;
}
# Try first the actual files, if they do not exist, then try $request_uri via `index.php`.
try_files $uri $uri/ /index.php/$request_uri;
我还在这里修复了隐藏文件正则表达式。
答案2
Nginx 重写正则表达式没有 $0 变量。您必须用它支持的内容替换它。
答案3
请用
$uri or $request_uri
而不是 $0 。