doujiaohuo1096 2015-10-09 04:51
浏览 140
已采纳

nginx php友好的URL重定向,不会干扰index.php导致/ index

I've tried so many different configurations to enable permanent redirection of any request ending with .php to redirect to itself without .php.

The issue is, I can't get a rule to redirect requests made to any directory with /index.php to redirect to / instead of /index.

Example:

Desired behavior = /blog/index.php -> /blog/ Current behavior = /blog/index.php -> /blog/index

Is there a clean solution to have any request containing "index.php" to remove itself from the request to simply /, all while still removing .php from all other requests not including index.php?

The two problem lines I can't get to function as desired:

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

Config:

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

}
  • 写回答

1条回答 默认 最新

  • douxing2652 2015-10-10 06:48
    关注

    You're likely experiencing the issue with your browser having your prior 301 Moved Permanently redirects in its cache, thus some of your newer code would not be having any effect.

    Clear the cache, and try something like this:

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

    The above line supports stripping out not only index.php, but also just index as you might have from your earlier question, as well as just .php, yet it preserves the possible query string from $args, too.

    To avoid having support for stripping just index, still supporting the rest of the features as above, use the following instead:

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

    P.S. The original explanation of this trick is here: nginx redirect loop, remove index.php from url.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧