nginx php友好的URLredirect,而不会干扰index.php导致/ index

我已经尝试了很多不同的configuration,以便永久redirect以.php结尾的任何请求,以便在没有.php的情况下redirect到自身。

问题是,我不能得到一个规则redirect到/index.php任何目录的请求redirect到/而不是/ index。

例:

期望的行为= /blog/index.php – > / blog /当前行为= /blog/index.php – > / blog / index

有没有一个干净的解决scheme,有任何请求包含“index.php”从请求中删除自己/ /,虽然仍然从所有其他请求中删除.php不包括index.php?

两个问题行我不能达到所需的function:

if ($request_uri ~* "^(.*/)index\.php$") { return 301 $1; } if ($request_uri ~ ^/(.*)\.php$) { return 301 /$1; } 

configuration:

 # Upstream upstream backend { server unix:/var/run/php5-fpm.sock; } server { listen 443 ssl; server_name mysite.net; # Serving root /var/www/html/mysite; charset utf-8; index index.php; # Resources location / { try_files $uri $uri/ @extensionless-php; } location @extensionless-php { rewrite ^(.*)$ $1.php last; } location ~* /includes/(.+)\.php$ { deny all; } location ~ \.php { try_files $uri =404; fastcgi_pass backend; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } # Status location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; } } 

您的浏览器可能已经遇到了您之前的301 Moved Permanently缓存中的301 Moved Permanently重定向问题,因此您的一些较新的代码不会有任何效果。

清除缓存,然后尝试如下所示:

 index index.php; if ($request_uri ~ ^/([^?]*?)(?:(?<=/)index(?:\.php)?|\.php)(\?.*)?$) { return 301 /$1$2; } 

上面的代码段不仅支持index.php ,而且还可以像刚刚提到的问题那样仅仅index .php ,但是它也保留了$args可能的查询字符串。

为了避免支持剥离index ,仍然支持上面的其他功能,请使用以下代码:

 if ($request_uri ~ ^/([^?]*?)(?:(?<=/)index)?\.php(\?.*)?$) { return 301 /$1$2; } 

PS这个技巧的原始解释是在这里: nginx重定向循环,从url中删除index.php 。