如何将apache.htaccess转换为nginx



如何转换nginx、的以下条件

RewriteEngine on
RewriteRule ^([^.]+)/?$ index.php?$1 [L]
RewriteRule ^([^.]+)/([^.]+)/$ index.php?$1 [L]
RewriteRule ^([^.]+)/([^.]+)$ index.php?$1 [L]
RewriteRule ^([^.]+)/([^.]+)/([^.]+)$ index.php?$1 [L]
RewriteRule ^([^.]+)/([^.]+)/([^.]+)/$ index.php?$1 [L]
RewriteRule ^([^.]+)/([^.]+)/([^.]+)/([^.]+)$ index.php?$1 [L]
RewriteRule ^([^.]+)/([^.]+)/([^.]+)/([^.]+)/$ index.php?$1 [L]

我需要将apache.htaccess转换为Nginx配置,如果有人知道解决方案,请帮助我,谢谢。

我已经使用一些在线工具将.htaccess文件转换为Nginx配置,但它不起作用。

如果我把URL放在浏览器中,就会自动下载index.php文件。我已经检查了info.php,但fpm也运行良好。我不知道如何解决这个问题。

这里我提到了我的Nginx conf文件:

server {
server_name example.com;
root /home/example/public_html;
index  index.php;
access_log  /var/log/nginx/example/example-access.log;
error_log  /var/log/nginx/example/example-error.log;
location / {
rewrite ^/([^.]+)/?$ /index.php?$1 break;
rewrite ^/([^.]+)/([^.]+)/$ /index.php?$1 break;
rewrite ^/([^.]+)/([^.]+)$ /index.php?$1 break;
rewrite ^/([^.]+)/([^.]+)/([^.]+)$ /index.php?$1 break;
rewrite ^/([^.]+)/([^.]+)/([^.]+)/$ /index.php?$1 break;
rewrite ^/([^.]+)/([^.]+)/([^.]+)/([^.]+)$ /index.php?$1 break;
rewrite ^/([^.]+)/([^.]+)/([^.]+)/([^.]+)/$ /index.php?$1 break;
}
location ~ ^/(?:.htaccess) {
deny all;
}
location ~ [^/].php(/|$) {
try_files $uri =404;
fastcgi_split_path_info ^(.+.php)(/.+)$;
fastcgi_pass unix:/run/php/php5.6-fpm-example.com.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}

}

GetPageSpeed转换器提供正确的结果:

server {
server_name example.com;
rewrite ^/([^.]+)/?$ /index.php?$1 last;
rewrite ^/([^.]+)/([^.]+)/$ /index.php?$1 last;
rewrite ^/([^.]+)/([^.]+)$ /index.php?$1 last;
rewrite ^/([^.]+)/([^.]+)/([^.]+)$ /index.php?$1 last;
rewrite ^/([^.]+)/([^.]+)/([^.]+)/$ /index.php?$1 last;
rewrite ^/([^.]+)/([^.]+)/([^.]+)/([^.]+)$ /index.php?$1 last;
rewrite ^/([^.]+)/([^.]+)/([^.]+)/([^.]+)/$ /index.php?$1 last;
}

注意last指令。这是正确的。它将确保NGINX将再次启动位置搜索,以查看哪些指令适用于重写的URI/index.php。然后它最终会出现在您的location ~ [^/].php(/|$) { ... }中,并且将应用PHP-FPM进行处理的指令。

有了break,事情就不起作用了,因为重写URL后就没有新的位置搜索了。URI保持为CCD_ 5,但来自CCD_;转到";应用它的指令。

更新2022-03-18

正如@Danila Vershinin所指出的,rewrite语句应该以last而不是break结尾。


你可以试试这种

location / {
rewrite ^/([^.]+)/?$ /index.php?$1 break;
rewrite ^/([^.]+)/([^.]+)/$ /index.php?$1 break;
rewrite ^/([^.]+)/([^.]+)$ /index.php?$1 break;
rewrite ^/([^.]+)/([^.]+)/([^.]+)$ /index.php?$1 break;
rewrite ^/([^.]+)/([^.]+)/([^.]+)/$ /index.php?$1 break;
rewrite ^/([^.]+)/([^.]+)/([^.]+)/([^.]+)$ /index.php?$1 break;
rewrite ^/([^.]+)/([^.]+)/([^.]+)/([^.]+)/$ /index.php?$1 break;
}

或者使用转换器或另一转换器。

最新更新