Skip to content

Instantly share code, notes, and snippets.

@bdwyertech
Created December 10, 2015 22:46
Show Gist options
  • Save bdwyertech/d5b1e097ea158a232aa3 to your computer and use it in GitHub Desktop.
Save bdwyertech/d5b1e097ea158a232aa3 to your computer and use it in GitHub Desktop.
Nginx - Nested locations and PHP-FPM
# => YOURLS URL Shortener Configuration
location /u/ {
root /var/www/api/urls/;
rewrite ^/(.*)/$ /$1/index.php last; # Enables index functionality (only really used for /u/admin/)
rewrite ^/u/(.*)$ /$1 break; # Strips /u/ from the URI for static files
try_files $uri /u/yourls-loader.php$is_args$args;
# => API PHP-FPM
location ~ \.php$ {
fastcgi_split_path_info ^/u(.+?\.php)(.*)$;
try_files $fastcgi_script_name =404;
include /etc/nginx/fastcgi_params;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
#fastcgi_param PATH_INFO $fastcgi_path_info;
#fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
fastcgi_pass unix:/var/run/pipeline.sock; # port where FastCGI processes were spawned
}
}
@bdwyertech
Copy link
Author

So, here's the deal. The only way this will EVER hit the PHP block is if it is prepended with with /u/ and ends in .php.

In this case, we can't use an index (the page called if the requested URL ends in /, e.g. test.com/u/admin/ . The regex here will capture any URI starting and ending with a / and redirect it with index.php appended, pretty slick eh? last causes it to be able to leave the current location block.

The second rewrite is for static files. This will strip the /u/ from the URI. The try files will then attempt to pick up the static file, otherwise ship the request to PHP.

The PHP block needs to strip the /u from the request again, so that is best done with fastcgi_split_path_info

We then put a try_files UNDERNEATH the split_path_info to ensure the presence of the script.

PATH_INFO and PATH_TRANSLATED probably are not necessary, but were part of this whole experiment. They are cool too.

HOPEFULLY, NginX fixes try_files and ALIAS soon, then we won't need all of this fancy rewrite stuff 💯

@aaronk6
Copy link

aaronk6 commented Aug 30, 2017

Awesome, thanks! I nearly gave up before I finally found this.

@H-s-O
Copy link

H-s-O commented Aug 20, 2019

Oh boy, this saved my sanity after hours of pulling my hair off. What a clusterfuck nested locations are.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment