nginx与php和重写规则

时间:2012-07-24 17:06:43

标签: php nginx rewrite

我想用php设置我的nginx服务器,以及一个简单的重写规则。我试图制作一个重写规则,任何指向不存在的文件或目录的URL都会重写为/index.php?q=。我创建了这个nginx.conf:

events {
}

http {
  include fastcgi.conf;
  server {
    listen          80;
    server_name     www.example.com;
    index           index.php;
    root            /var/www/html/www.example.com;
    location / {
      index     index.php;
      if (!-f $request_filename) {
        rewrite ^/(.*)$ /index.php?q=$1 last;
      }
      if (!-d $request_filename) {
        rewrite ^/(.*)$ /index.php?r=$1 last;
      }
    }
    location ~ \.php {
      try_files $uri =404;
      fastcgi_pass 127.0.0.1:9999;
    }
  }
}

这有效,但并非在所有情况下都有效。它完全重写了像tihs:

http://www.example.com/111/222/333

但是两个案件不能按我的意思运作:

http://www.example.com/111/222/333.php

丢弃404错误。

www.example.com/forum/index.php存在,因此www.example.com/forum/index.php在论坛目录中执行index.php,这很好。但是www.example.com/forum url会重写为/index.php,而不是像我想要的那样在论坛目录中执行index.php。

我如何解决这两个问题?

谢谢!

2 个答案:

答案 0 :(得分:1)

您的配置绝对错误,请用一行替换位置/内容:

try_files $uri $uri/ /index.php?q=$uri;

答案 1 :(得分:0)

如果要重定向到特定目录中的索引文件,则需要将重定向格式设置为类似

rewrite ^/((.*/)*)(.*)$ /$1index.php?q=$3