I'm trying to write an Nginx config with the following semantics, expressed in hopefully-readable 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
}
How do I do this? I have a decent sense of Apache configuration, but I don't have a good enough grasp on Nginx to sort out the semantics of try_files
and location
matching and internal redirects and stuff. Any tips on how I should structure this?
For reference, the mod_rewrite
-based configuration I'm currently using with Apache is
# 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>
You could simplify this (NGINX is all about being simple) by using the try_files directive. This allows you to cascade scenarios in one statement.
In your case since you want to redirect any directory call to index.php, you can have it try the specific file first, and then index.php:
Also I would adjust your location detection for php:
Doing this, you don't need a "location /" entry. Your complete config for this site would be something like this (I am using php-fpm, your php location may vary):
It's better to get a basic understanding of how nginx works before writing a config for it. Read howtos and examples from http://wiki.nginx.org/Configuration
Nginx config is not about if-then-else. There's distinct stages of processing each request, and you just define what are parameters of each stage.
You can make use of this template: