Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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;
    server_name  www.example.com;

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

    root   /var/www/html/example.com;
    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/example.com$fastcgi_script_name;
        include        fastcgi_params;
    }

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

    location ~ /\.ht {
        deny  all;
    }

    location /404.php {
        internal;
        return 404;
    }
}

Any help would be appreciated. Thanks!

share|improve this question
add comment

2 Answers

up vote 0 down vote accepted

You could probably use try_files and @LOCATION. Something like this (simplified, untested example):

server {
    listen 80;
    server_name www.example.com;

    root /var/www/html/example.com;
    index index.php index.html index.htm;

    location / {
        try_files /$uri @PROFILEALIAS;
    }

    location ~ \.php$ {
        fastcgi_pass example_fast_cgi;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location @PROFILEALIAS {
        fastcgi_pass example_fast_cgi;
        fastcgi_param SCRIPT_FILENAME $document_root/profile.php;
        fastcgi_param QUERY_STRING url=$uri;
        include fastcgi_params;
    }
}

The trick with try_files is to avoid sending requests for static files to PHP as profile pages. Similar thing can be accomplished with regex locations, but this is more efficient.

share|improve this answer
    
Perfect! Thanks. –  user1721724 Jul 7 '13 at 19:44
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.