【问题标题】:nginx php friendly URL redirection without interfering with index.php causing /indexnginx php 友好的 URL 重定向而不干扰 index.php 导致 /index
【发布时间】:2016-01-06 22:08:06
【问题描述】:

我已经尝试了很多不同的配置来启用以 .php 结尾的任何请求的永久重定向,以重定向到没有 .php 的自身。

问题是,我无法获得将请求重定向到使用 /index.php 的任何目录以重定向到 / 而不是 /index 的规则。

例子:

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

是否有一个干净的解决方案让任何包含“index.php”的请求从简单的/请求中删除自己,同时仍然从所有其他请求中删除 .php,不包括 index.php?

我无法按预期运行的两条问题线:

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

配置:

# 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;
}

}

【问题讨论】:

  • 我建议发布您目前/迄今为止尝试过的内容

标签: php redirect nginx


【解决方案1】:

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

清除缓存,然后尝试以下操作:

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

以上行不仅支持剥离index.php,还支持剥离just index as you might have from your earlier question,以及仅剥离.php,但它还保留了来自$args 的可能查询字符串。

为避免仅支持剥离 index,仍支持上述其余功能,请改用以下内容:

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

附:这个技巧的原始解释在这里:nginx redirect loop, remove index.php from url.

【讨论】:

  • 哇,太完美了。谢谢你。我想我只是没有真正认识到您链接的解决方案,因为我在询问之前搜索时实际上看到了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-20
  • 2014-05-19
  • 2012-12-07
  • 2012-02-24
  • 2019-08-01
  • 2012-03-18
  • 2014-02-24
相关资源
最近更新 更多