Showing posts with label Web Server. Show all posts
Showing posts with label Web Server. Show all posts

Apache - Selectively Disabling mod_rewrite

Say you have redirect a domain from .net to .com and have a rule such as:

# Rewrite to the new domain and add "www"
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteRule ^/(.*)$ http://www.domain.com/$1 [R=301,L]

These are catch all rules, which check if the host is domain.net, if not it just redirects it to it. (See the motives why you should use "www" or base domains and never both on this page)

In this scenario, if you want to disable rewriting for a certain folder for the .net domain, you can add the following rule at the top of the code:

RewriteRule ^/oldfolder(.*)? - [L]
# Rewrite to the new domain and add "www"
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteRule ^/(.*)$ http://www.domain.com/$1 [R=301,L]

Here we will match the folder and stop there, thereby serving the page from the alternative domain name (a .net domain) for the specified folder.

http://www.domain.net/oldfolder/somethingelse

If you need more information on www or non-www URL rewriting, please see the www-redirection tutorial page.

Apache - URL Rewriting To WWW or non-WWW Domains Names

A small error with web server configurations continues to be a source of headaches on the web: the lack of redirection to the WWW sub-domain.

To do the rewriting I'll be focusing on Apache's mod_rewrite, which is one of the more widely available solutions to the problem.

This code is what you need if you use a .htaccess file on your server:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.chosendomain\.com$ [NC]
RewriteRule ^(.*)$ http://www.chosendomain.com/$1 [R=301,L]

There's another option when you want to keep it stored in a safer location, which is including it in Apache's httpd.conf file:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.chosendomain\.com$ [NC]
RewriteRule ^/(.*)$ http://www.chosendomain.com/$1 [R=301,L]

These two blocks of code have slight differences. Notice RewriteRule here has a forward slash, replacing the RewriteBase / directive on the previous example. While they do the same thing, they are not interchangeable depending on which configuration file you use.

Don't forget the escape character for the dot on RewriteCond rules - even though it is unlikely you'll match something.

If after you've done this, you need to exclude some folders/paths from the URL redirection you've just inserted, see the instructions on the Selectively Disabling mod_rewrite post.