经过大约2个小时的谷歌搜索和尝试各种各样的事情后,我求助于你。
任务: 将空白URL重写为某些内容,将其他所有内容重写为nginx中的其他内容。
所以,如果我导航到subdomain.somedomain.tld,我想得到index.php,如果我去subdomain.somedomain.tld / BlAaA,我会被重定向到index.php?url = BlAaA。例外是/ img,/ include和index.php本身下的文件。它们不会被重写。
第二部分已经发挥作用,白名单也是如此,但我无法弄清楚或找到完成整个想法的东西。
工作部分:
server {
listen 80;
server_name subdomain.domain.tld;
location / {
include php.conf;
root /srv/http/somefolder/someotherfolder/;
if ( $uri !~ ^/(index\.php|include|img) ){
rewrite /(.*) /index.php?url=$1 last;
}
index index.php;
}
}
@ pablo-b提供的答案几乎解决了我的问题。 这种方法只存在两个问题:1:PHP-FPM现在需要在/etc/php/php-fpm.conf下的/ include /(例如style.css,background.jpg)下设置文件扩展名.limit_extensions。我原来的php.conf按照
的方式工作location ~ \.php {
#DO STUFF
}
nginx不喜欢,因为它有点覆盖你的建议中的位置/index.php部分。但是,如果有足够的时间,我可以解决这个问题。
2:$ request_uri为我的url =参数输出“/ whatever”,而不是“what”。我可以在我的PHP代码中解析“/”,当然,但我的原始解决方案没有添加前导“/”。有什么优雅的方法来解决这个问题吗?
答案 0 :(得分:2)
我建议避免if
并使用与使用的模式匹配方法相关的优先级(docs)来处理不同的位置:
#blank url
location = / {
return 302 http://subdomain.domain.tld/index.php;
}
#just /index.php
location = /index.php {
include common_settings;
}
#anything starting with /img/
location ^~ /img/ {
include common_settings;
}
#anything starting with /include/
location ^~ /include/ {
include common_settings;
}
#everything else
location / {
return 302 http://subdomain.domain.tld/index.php?url=$uri_without_slash;
}
在名为common_settings
的单独配置文件中:
include php.conf;
root /srv/http/somefolder/someotherfolder/;
index index.php;
编辑:在网址中删除了第一个斜杠:
在你的conf中,在任何server
指令之外:
map $request_uri $uri_without_slash {
~^/(?P<trailing_uri>.*)$ $trailing_uri;
}