.htaccessurl-rewritingvanity-url

.htaccess username url unless directory exists


I currently have the following code in place to give users their own URL for their username:

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?username=$1

However, any existing directories such as /about/ or /terms/ no longer work because this code has overwritten the URL.

Is there anwyay I can adjust this code to only point the URL to a profile if the file or directory doesn't already exist?


Solution

  • You should check if the folder actually exists, and if so enforce a rule that does not redirect. If those conditions do not match, then it will continue to the rules that do redirect.

    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    
    RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?username=$1
    RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?username=$1
    

    The -f flag means it exists as a file, and -d means a directory. Now if the requested file actually is a file or directory it will not continue to the redirect rules

    Also, you could shorten your redirect rule to:

    RewriteRule ^([a-zA-Z0-9_-]+)/?$ profile.php?username=$1
    

    The ? after the / means it will match with or without that character. Since the rest of the regex is unchanged this rule will tackle both cases at once.