我想用下面的语义编写一个Nginxconfiguration,用希望可读的psuedo-config表示:
location /dir1/ /dir2/ { if (matches a .php file) { serve with php } else if (matches a non-.php file) { serve as static content } else { 404 } } else { serve with /index.php }
我该怎么做呢? 我有一个体面的Apacheconfiguration的感觉,但我没有足够的把握Nginx的理清try_files和location匹配和内部redirect和东西的语义。 关于如何构build这个的任何提示?
作为参考,我目前使用的基于mod_rewrite的configuration是
# Any URL not corresponding to a directory gets rewritten to index.php RewriteCond $1 !^dir1/ RewriteCond $1 !^dir2/ RewriteRule ^(.*)$ ./index.php/$1 [L,QSA] # Allow access to files in any of the directories RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^(.*)$ - [L] # If either step above resulted in a php file, process it <FilesMatch "\.php$"> SetHandler application/x-httpd-php </FilesMatch>
你可以通过使用try_files指令来简化这个(NGINX就是简单)。 这允许您在一个语句中级联场景。
在你的情况下,因为你想redirect任何目录调用index.php,你可以让它先尝试特定的文件,然后index.php:
try_files $ uri index.php;
另外我会调整你的位置检测为PHP:
位置〜^(。+ \。php)(。*)$ {
[你的fastcgi块在这里]
}
这样做,你不需要一个“位置/”条目。 你对这个网站的完整configuration是这样的(我正在使用php-fpm,你的php位置可能会有所不同):
服务器{
server_name www.example.com;
root / path / to / docroot;
access_log / path / to / logfile;
error_log / path / to / errorlog;
index index.php;
try_files $ uri index.php;
位置〜^(。+ \。php)(。*)$ {
包括fastcgi_params;
fastcgi_index index.php;
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
fastcgi_param SCRIPT_FILENAME $ document_root $ fastcgi_script_name;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
}
}
在编写configuration之前,最好先了解一下nginx的工作原理。 阅读http://wiki.nginx.org/Configuration中的 howtos和示例
Nginxconfiguration不是关于if-then-else。 处理每个请求有不同的阶段,您只需定义每个阶段的参数。
你可以使用这个模板:
location ~ \.php$ { fastcgi_pass unix:/var/run/php/fcgi; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /var/www/localhost/htdocs$fastcgi_script_name; include /etc/nginx/fastcgi_params; } location / { root /some/folder; error_page 404 /index.php }