Multiple Vanity URLs with different pages in different directories

60 views Asked by At

I am trying to setup my .htaccess file to allow for multiple vanity URLs which is fine, but I'm running into issues with them with the pages being in different directories.

First vanity URL is setup and working fine, which works like this:

example.com/blognumber1 > example.com/inspiration/article.php?id=blognumber1

RewriteBase /inspiration/
RewriteCond %{REQUEST_FILENAME} !-d [NC]
RewriteCond %{REQUEST_FILENAME} !-f [NC]
RewriteRule ^(.*)$ article.php?id=$1 [QSA,L]

I am trying to add another one which would work like this:

example.com/supplier/test1 > example.com/profile.php?id=test1

Because the article.php page is in a different directory, I am having problems trying to code it, any help would be appreciated.

1

There are 1 answers

0
MrWhite On

Don't use a RewriteBase directive (which applies to the entire file) and make sure the more specific /supplier/test1 rule is first. For example:

RewriteEngine On

# Abort early if a directory or file is requested directly
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# Rewrite "/supplier/<test1>" to "profile.php?id=<test1>"
RewriteRule ^supplier/([^/]*)$ profile.php?id=$1 [QSA,L]

# Rewrite "/<blognumber1>" to "inspiration/article.php?id=<blognumber1>"
RewriteRule ^(.*)$ inspiration/article.php?id=$1 [QSA,L]

Note that the NC flag is not permitted on the RewriteCond directive when used with the filesystem checks -f and -d. If you check your error log you will probably see a stack of warnings.

On the /supplier/test1 rule, it only matches a single path segment after /supplier/, ie. it does not match /supplier/test1/something.

Your existing rule is rather generic as it literally matches anything. Perhaps restrict this to a single path segment also? Or restrict the regex to what constitutes a blognumber.

Optimisation

As a further optimisation you could also abort early if a .php file (or a URL that looks-like a .php file) is requested. Unless you have valid "supplier" or "blog" URLs that end in .php? For example, immediately after the RewriteEngine directive:

# Abort early if any `.php` URL is requested (includes rewritten URLs)
RewriteRule \.php$ - [L]

You can extend this for any URL that looks-like it contains a file extension, which should naturally include your static assets and therefore avoid the filesystem check. For example:

RewriteRule \.\w{2,5}$ - [L]