我想用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:这样的utl
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。
我该如何解决这两个问题?
谢谢!
您的配置完全错误,请用单行替换位置/内容:
try_files $uri $uri/ /index.php?q=$uri;
如果你想重定向到特定目录中的索引文件,你需要将重定向格式设置为这样
rewrite ^/((.*/)*)(.*)$ /$1index.php?q=$3