索引文件在nginx中redirect

脚本

我有一个网站的结构如下:

/index.html /about/index.html /contact/index.php /contact/send_email.php 

我本来希望使URL更清洁,所以我会成为等效的结构:

 / => /index.html /about/ => /about/index.html /contact/ => /contact/index.html /contact/send_email.php => /contact/send_email.php 

基本上是一个Nginxconfiguration,从URI中删除所有的index.htmlindex.php文件名。

我的尝试configuration

 server { listen 80; root /home/www/mysite; server_name www.mysite.com; location ^~* /[az]+/index\.(html|php)$ { rewrite ^(/[az]+/)index\.(html|php)$ http://www.mysite.com$1? permanent; } try_files $uri $uriindex.html $uriindex.php =404; location ~ \.php$ { include /etc/nginx/fastcgi_params; fastcgi_pass unix:/var/run/php5.sock fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } } 

问题

简而言之 – 这是行不通的。 当我去/about/index.html 应该永久redirect到/about/但它只是停留在/about/index.html 。 我testing了正则expression式,他们似乎很好 – 即在重写工作中定义的捕获组。

你使用的是哪个版本的nginx?

我用nginx 1.4.2试过了你的configuration,它检测到一些语法错误:

  1. invalid location modifier "^~*"在您的第一个location指令 – 我改变了~
  2. unknown "uriindex" variable在您的try_files指令 – 我改变了$uriindex.html$uriindex.php$uri/index.html$uri/index.php

在这一点上,我相信设置大部分你想要的:

  1. 访问www.mysite.com/about/index.html您将被redirect到www.mysite.com/about/
  2. 访问www.mysite.com/contact/index.html您将被redirect到www.mysite.com/contact/
  3. www.mysite.com/contact/send_email.php没有redirect发生

现在www.mysite.com/index.htmlredirect到www.mysite.com/ ,您将需要另一个“位置”指令和重写规则:

 location ~ /index\.html$ { rewrite ^/index\.html$ http://www.mysite.com permanent; } 

而对于www.mysite.com/contact/将使用PHP-FPM作为www.mysite.com/contact/index.php脚本执行,您还需要一个特定的位置指令。 这里的fastcgi_index index.php行非常重要:

 location = /contact/ { include /etc/nginx/fastcgi_params; fastcgi_pass unix:/var/run/php5.sock fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } 

希望这可以帮助 :)