我发现很多人和我有同样的问题,但我找不到合适的解决方案。
我正在通过流浪汉和宅基地运行NGINX服务器。在生产端我使用的是apache,因此我有一个htaccess:
RewriteEngine On
RewriteCond %{REQUEST_URI} !(^cms-system/public|^assets)
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ cms-system/public/$1 [L]
我使用此htaccess将所有网址(cms-system / public和assets除外)重写为我的index.php,该文件位于cms-system / public中。
我尝试使用此工具将此htaccess转换为nginx配置:https://winginx.com/en/htaccess哪个效果不好..我做了一些调整。异常规则有效,但是我无法重写index.php。有人可以帮助我吗?
server {
listen 80;
listen 443 ssl http2;
server_name company.dev;
root "/home/vagrant/company/";
index index.html index.htm index.php;
charset utf-8;
location ~ ^/cms-system/public/(.*) {
}
location ~ ^/assets/(.*) {
}
location / {
if ($request_uri !~ "-f"){
rewrite ^(.*)$ /cms-system/public/$1 break;
}
}
# original location rule
# location / {
# try_files $uri $uri/ /index.php?$query_string;
# }
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
access_log off;
error_log /var/log/nginx/company.dev-error.log error;
sendfile off;
client_max_body_size 100m;
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors off;
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
}
location ~ /\.ht {
deny all;
}
ssl_certificate /etc/nginx/ssl/company.dev.crt;
ssl_certificate_key /etc/nginx/ssl/company.dev.key;
}
答案 0 :(得分:6)
这就是你所需要的:
location / {
try_files $uri @rewrite;
}
location @rewrite {
if ($uri !~* "^/(cms-system\/public|assets)$") {set $block "A";}
if (!-e $request_filename) {set $block "${block}B";}
if ($block = "AB") {rewrite ^(.*)$ /cms-system/public/$1 last;}
}
而不是:
RewriteEngine On
RewriteCond %{REQUEST_URI} !(^cms-system/public|^assets)
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ cms-system/public/$1 [L]
出于安全原因,建议使用此方法:
location ~* \.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|\.php_ {
deny all;
}
另请阅读:
porting-standard-apaches-mod_rewrite-rules-to-nginx
How do I convert mod_rewrite (QSA option) to Nginx equivalent?