NGINX rewrite for vanity URLs when file doesn't exist (try_files and rewrite together)

user1721724 asked:

I’m trying to get vanity URLs on my server. If the file path from the URL doesn’t exist, I want to rewrite the URL to profile.php, but if my users have periods in their usernames, their vanity URL doesn’t work.

Here is my conf block.

server {
    listen       80;

    rewrite ^/([a-zA-Z0-9-_]+)$ /profile.php?url=$1 last;

    root   /var/www/html/;
    error_page 404 = /404.php;

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires 1y;
        log_not_found off;

    location ~ \.php$ {
        fastcgi_pass  example_fast_cgi;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /var/www/html/$fastcgi_script_name;
        include        fastcgi_params;

    location / {
        index  index.php index.html index.htm;

    location ~ /\.ht {
        deny  all;

    location /404.php {
        return 404;

Any help would be appreciated. Thanks!

My answer:

You can add a period \. to the regex, if it’s meant to be valid in a user name.

But the best approach is to handle these within your application using the front controller pattern, like many other popular web applications do.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.