Apache2 - rewrite a bunch of specified pathname URLs to one URL
- by James Nine
I need to rewrite a bunch of urls (about 100 or so) for SEO purposes, and there may be more being added in the future (probably another 50-100 later on). I need a flexible way of doing this and so far, the only way I can think of is to edit the .htaccess file using the rewrite engine.
For example, I have a bunch of urls like this (please note that the query string is irrelevant, and dynamic; it could be anything. I was only using them purely as an example. I am only focusing on the pathname--the part between the hostname and query string, as marked in bold below):
http://example.com/seo_term1?utm_source=google&utm_medium=cpc&utm_campaign=seo_term
http://example.com/another_seo_term2?utm_source=facebook&utm_medium=cpc&utm_campaign=seo_term
http://example.com/yet_another_seo_term3?utm_source=example_ad_network&utm_medium=cpc&utm_campaign=seo_term
http://example.com/foobar_seo_term4
http://example.com/blah_seo_term5?test=1
etc...
And they are all being rewritten to (for now): http://example.com/
What's the most efficient/effective way of doing this so that I may be able to add more terms in the future?
One solution I came across is to do this (in the .htaccess file):
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ / [NC,QSA]
However, the problem with this solution is that even invalid urls (such as http://example.com/blah) will be rewritten to http://example.com instead of giving a 404 code (which is what it is supposed to do anyway). I'm still trying to figure out how all this works, and the only way I can think of is to write 100 more RewriteCond statements (such as: RewriteCond %{REQUEST_URI} =/seo_term1 [NC,OR]) before the RewriteRule directive. For example:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} =/seo_term1 [NC,OR]
RewriteCond %{REQUEST_URI} =/another_seo_term2 [NC,OR]
RewriteCond %{REQUEST_URI} =/yet_another_seo_term3 [NC,OR]
RewriteCond %{REQUEST_URI} =/foobar_seo_term4 [NC,OR]
RewriteCond %{REQUEST_URI} =/blah_seo_term5 [NC]
RewriteRule ^(.*)$ / [NC,QSA]
But that doesn't sound very efficient to me. Is there a better way?