# How can I create a location in nginx that works with AND without a trailing slash?

Right now, I have this:

location ~ ^/phpmyadmin/(.*)${ alias /home/phpmyadmin/$1;
}


However, if I visit www.mysite.com/phpmyadmin (note the lack of trailing slash), it won't find what I'm looking for and 404. I assume because I don't include the trailing slash. How can I fix this?

-

It might be in the regular expression that you're using --

location ~ ^/phpmyadmin/(.*)$ The above will match /phpmyadmin/, /phpmyadmin/anything/else/here, but it won't match /phpmyadmin because the regular expression includes the trailing slash. You probably want something like this: location ~ /phpmyadmin/?(.*)$ {
alias /home/phpmyadmin/$1; }  The question mark is a regular expression quantifier and should tell nginx to match zero or one of the previous character (the slash). HTH - Thank you! And thank you for the explanation, as well. Will come in handy in the future. – Rob Apr 3 '12 at 6:08 Why wouldn't you just use location /phpmyadmin { alias /home/phpmyadmin; }  ? - Because that wasn't working for me. See here: serverfault.com/questions/375602/… – Rob Apr 3 '12 at 5:35 @Rob Did you try it without the trailing slash on the alias directive? – Shane Madden Apr 3 '12 at 17:04 The better solution: location ~ ^/phpmyadmin(?:/(.*))?$ {
alias /home/phpmyadmin/$1; }  Ensure that server has permissions to /home/phpmyadmin first. - This redirect will only rewrite URLs with and without the trailing slash. Anything that comes after the slash won't be overwritten. domain.com/location => redirected to domain.com/new/location domain.com/location => redirected to domain.com/new/location domain.com/location/other => not redirected server { # 301 URL Redirect rewrite ^/location/?$ /new/location permanent;
}

-

Have you tried using try_files directive?

try_files $uri$uri/ =404;

-