Take the following config as an example:
location / {
try_files $uri $uri/ /index.php?$args;
}
location /a-random-website/ {
try_files $uri $uri/ /a-random-website/index.php?$args;
}
location /another-random-website/ {
try_files $uri $uri/ /another-random-website/index.php?$args;
}
location /something/wordpress/ {
try_files $uri $uri/ /something/wordpress/index.php?$args;
}
location /something/another-wordpress/ {
try_files $uri $uri/ /something/another-wordpress/index.php?$args;
}
Everything works fine as it should. However, would it be possible to simplify this and/or not needing to specify each folder? Maybe by using a regex that would capture each folder in the path? I've tried the following (based on this answer) but doesn't seem to be working in my case:
location / {
try_files $uri $uri/ /index.php?$args;
}
location /([^/]+)/ {
try_files $uri $uri/ /$1/index.php?$args;
}
location /([^/]+)/([^/]+)/ {
try_files $uri $uri/ /$1/$2/index.php?$args;
}
The download of index.php
(as per issue in comment) would happen because when you introduced new regex locations, they will be prioritized based on their placement in the configuration file. So you would need to place your .php
location at the top to prioritize it, and make sure to anchor (put ^
) your regular expressions like so:
# Should be placed topmost:
location ~ \.php$ {
# ... PHP handling directives ...
}
# next, the try_files blocks
location ~ ^/([^/]+)/? {
try_files $uri $uri/ /$1/index.php?$args;
}
location ~ ^/([^/]+)/([^/]+)/? {
try_files $uri $uri/ /$1/$2/index.php?$args;
}
That said, I highly recommend against using regular expressions where your initial config is perfectly fine using prefixed location which are a lot faster. If we're talking about only squeezing few such locations into couple of NGINX blocks to gain convenience of not having to edit NGINX on newly added locations, as it doesn't take much time. And I don't think you add new such locations every hour. If you do, you might want to look into templating your NGINX configurations using tools like Ansible. All better than regex locations IMHO.