首页 > 解决方案 > 在 NGINX conf 中外部重定向 URL 以添加斜杠并使用 php 文件

问题描述

我是这个网站的新手,也是 NGINX 的新手,所以请友好。我最近切换到 AWS Elasticbeanstalk,需要 NGINX 配置方面的帮助。我想做一些我知道并测试过的重定向,它可以在 apache2 中使用 .htaccess,但我无法使用 NGINX 完成。

我希望我的所有 URL 都以 trainling 斜杠结尾,如果是,请检查 $uri 是否是目录,如果不使用姓氏作为脚本名称,请使用 index.php,如下所示:

我想要这个 URL: 使用这个脚本:

https://localhost/ -> ./index.php

https://localhost/page/ -> ./page.php

https://localhost/folder/page/ -> ./folder/page.php

https://localhost/folder/page/?param=foo -> ./folder/page.php?param=foo

我在 .htaccess 中使用此配置使其在 apache2 中的行为如下所示:

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1/ [R,L]

# add a trailing slash   
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule . %{REQUEST_URI}/ [L,R=301]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]

如何将此 .htaccess 转换为 NGINX 配置文件?

提前致谢。

标签: phpapache.htaccessnginx-reverse-proxy

解决方案


试试这个,记得插入后重启:

location / {
    try_files $uri $uri.html $uri/ @extensionless-php;
    index index.html index.htm index.php;
}

location ~ \.php$ {
    try_files $uri =404;
}

location @extensionless-php {
    rewrite ^(.*)$ $1.php last;
}

推荐阅读