Categories
Apache mod-rewrite and htaccess related Articles

Redirect domain with homepage exception htaccess

In this article I will show you how to write a RewriteRule for htaccess to redirect a website to another website with homepage exception.
I will show you a RewriteRule that does a 301 redirect from your website to another external site. The redirection will get applied to all URLs on your website except the homepage /.

If you are new to htaccess , you can follow our basic htaccess guide .htaccess tutorial for beginners .

Before we get to the rule, let’s first understand the requirement :
Suppose, we have two domains

  • example1.com
  • example2.com

Both domains are on different webservers, and we want that all traffic from example1.com should get redirected to example2.com with homepage exception meaning that the “example1.com/” will not get redirected to example2 domain while all other URLs ie: “example1.com/*” will use the redirection.

There are two different ways to do such redirection with an htaccess file.You can either use mod-rewrite or mod-alias. These two Apache modules can be used for URL redirection on Apache.

Redirect domain with homepage exception using RedirectMatch

One of the easiest way to do this type of redirection with htaccess is a simple one liner RedirectMatch directive. This directive is part of Apache mod-alias. You can use the code below in your htaccess file :

RedirectMatch 301 ^/(.+)$ https://example.com/$1

RedirectMatch directive use regular expression based pattern so the match becomes easier. The code above will redirect all requests except the homepage from your example1 domain to the another domain.

Note : The code should be placed in root htaccess in your example1 domain.

If you want to remove the homepage exception, just change the regex pattern to ^/(.*)$ .

Redirect domain with homepage exception using RewriteRule

You can redirect your domain with RewriteRule directive. RedirectMatch can fail to work if your htaccess contains other directives, in that case RewriteRule is the solution. Just place the code at the top of your htaccess file :

RewriteEngine On
RewriteRule ^(.+)$ https://example2.com/$1 [R=301,L]

In case your destination domain is on the same server and pointing to the same document root then both the Redirects I showed above might cause an infinite redirect error. Use the following rule if both domains are on the same server :

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?example1\.com$
RewriteRule ^(.+)$ https://example2.com/$1 [L,R=301]

I hope this article was helpful, if it really helped you and you want to say thanks just click on the coffee button below to buy me a coffee. Thanks.

Categories
Apache mod-rewrite and htaccess related Articles

How to set subfolder as root folder with htaccess

This article explains how to set a subfolder as root folder for your domain name using RewriteRule directive in an htaccess file.

With an htaccess file , you can easily manage your site URLs the way you want to. You can shorten a long URL, you can completely change the appearance of your site URLs and you can do even more.
If you are new to htaccess and URL rewriting , I have written a Short htaccess tutorial for beginners that you might find interesting and helpful.

This post will show you how to set your subdirectory as main directory using a few lines of htaccess code.
Assuming your folder structure is as follows :

  • /root
  • /subfolder 1
  • /subfolder 2
  • index.php
  • .htaccess

As you can see we have two subfolders in the root directory , to access files or folders inside subfolder1 we have to type https://example.com/subfolder1/file and to access any files/folders in root we just type https://example.com/file .

Okay ,
if you want to set your subfolder1 as your main directory, by setting “subfolder1” as main directory here I mean to say your subfolder will be treated as your root folder. Any requests you receive on your domain via root folder will be mapped to the subfolder1.

The following basic htaccess rule rewrites your root folder and any root requests to /subfolder

RewriteEngine On
#rewrite root to subfolder
#including all files and folders
#exclude the destination folder
RewriteCond %{REQUEST_URI} !^/subfolder1 [NC]
RewriteRule ^(.*)$ /subfolder1/$1 [L]

Okay, isn’t it as simple as ABC?

The rule does the following :

It redirects any files and folders from root to subfolder.
The redirection is internal so your browser won’t redirect and your visitors will not be able to notice it.
The URL example.com/file.php will show you the contents of example.com/subfolder1/file.php
.

Some important things to take note of in the rule :

  • We excluded the destination folder using RewriteCond directive as it’s important to avoid rewrite loop error.
  • We used ^(.*)$ instead of ^(.+)$ in the pattern above so that any empty URI (Root folder “/”) can also map to the subfolder1.
  • Use the rule in your root htaccess only and remove your subfolder1 htaccess if it exists.

Okay, the rule above does its job perfactly but there is still something important to implement. You now have two URLs pointing to the same location, ie . example.com/file.php and example.com/subfolder1/file.php both URLs will show you the same content which can cause duplicate content issues on search engines.
If you care about your site SEO, you will need to fix it. You can set up a 301 redirect from your subfolder1 URLs to the root so that search engines can index only one URL.

The following is the complete version of the htaccess rules to map root to subfolder

RewriteEngine On
#301 Redirect subfolder1 to root
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^subfolder/(.*)$ /$1 [L,R=301]
#rewrite root to subfolder
#including all files and folders
#exclude the destination folder
RewriteCond %{REQUEST_URI} !^/subfolder1 [NC]
RewriteRule ^(.*)$ /subfolder1/$1 [L]

I hope this article was helpful. If you still need any help regarding root to subfolder redirection , just leave a comment below .I would love to help you out with this. Thanks.

Categories
Apache mod-rewrite and htaccess related Articles

How to remove folder name from URL with htaccess

The most common use of an htaccess file is to shorten and rewrite URLs so that they can look clean and preety.
Short URLs are often easy to remember and type in a web browser. So instead of typing a long URL you can just use its clean version to go to the original page.

In this article , I am going to show you how to shorten a directory URL with htaccess.

Assuming our directory structure is as shown in the pic below :
folder structure

As you can see above, we have a subfolder named “folderA” in the root directory. The subfolder has 2 files

  1. index.html
  2. index2.html

To access the files by a web browser , we have to type https://example.com/folderA/index2.html .
This is the actual path location to visit the file but if you are not happy with the URL and want to shorten it, say you want to remove the folder name , you can easily do this with
RewriteRule directive.
After removing the folder name from URL , the URL to the file will look something like :
https://example.com/index2.html.

In the next section below, I will show you how a folder name can be removed from URL using htaccess.

Removing folder name from URLs with htaccess file

It’s not a rocket science to remove the folder name from URLs. You can easily do this with just a few lines of code in an htaccess file.
Here I am taking the exect same URL example I mentioned above.

To remove the folder A you can use the following lines of code in your htaccess file . Remember to place the code at the top of your htaccess in root.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.+) /folderA/$1 [L]

That’s it.
With those lines set in your htaccess file, you will be able to access your index2.html file in “folderA” by visiting example.com/index.html . It makes it as if you requested the file from root folder.

The rule above doesn’t remove folder name from the URL , it just makes it so that you can use the new version to access the file but the file can also be visited by typing the original location. This leaves you with two different URLs pointing to the same location. If you want to remove the folder name completely , you can use the following rule instead :

RewriteEngine on
RewriteRule ^folderA/(.+)$ /$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.+) /folderA/$1 [END]

I have also written an htaccess tutorial for people who are new to htaccess and wish to learn , if you are interested, you can find the tutorial On this link
I hope the post was helpful. Thanks for reading it.

Categories
Apache mod-rewrite and htaccess related Articles

Block a specific http referer using RewriteRule in htaccess

HTTP_REFERER header contains URL of the site where the visiter came from. If you came to this site from Google search the domain in the REFERER header will be google.com .
REFERER header contains the full URL string excluding the fregment part which isnt sent to the server.
With mod-rewrite you can manipulate the referer header using %{HTTP_REFERER} variable in RewriteCond directive.
This article shows how you can block access to a specific http referer using mod_rewrite in htaccess file .

Block a specific http referer using RewriteRule in htaccess

I am going to write a sample rule here to block access to example.com domain. You can modify the rule and change the referer domain to whatever domain you want to disallow access to .
The following rule completely blocks example.com . This won’t allow any referer URLs from the example.com domain to your site.

RewriteEngine On
RewriteCond %{HTTP_REFERER} example\.com [NC]
RewriteRule .* - [F]

Explaination :

  • RewriteEngine On tells server to turn on the engine for rewriting URLs. You can remove this line if it’s already present in your htaccess file and put the other two lines just bellow that.
  • RewriteCond %{HTTP_REFERER} example\.com [NC] this creates a condition under which the rule executes . This says “if the refer header is = example.com” . If the condition is met then it sends a green signal to the RewriteRule line that follows it to run and if it’s not met then the rewriting is skipped and the rule is not triggered.
  • RewriteRule .* – [F] rewrites any requested path to F . The F represents a 403 forbidden error. The rule rewrites any request to a 403 error if the condition above it is met.

The RewriteRule posted above in code block blocks the entire example.com referer site meaning that no referer URLs from that domain to your site will be allowed. Clients will get a 403 forbidden error. However if you do not want to block the entire site but a specific URL or page, you can use the following in your htaccess file :

Block a specific referer URL with htaccess

RewriteEngine On
RewriteCond %{HTTP_REFERER} example\.com/thispage\.php [NC]
RewriteRule .* - [F]

This blocks access to a specific referer page example.com/thispage.php while other referer URLs from the domain will keep working normally.

Categories
Apache mod-rewrite and htaccess related Articles

How to set cookies for a specific http_host with htaccess?

This article explains how to set an http cookie for a specific http_host header with htaccess file using mod_rewrite.
With mod_rewrite we can set cookies using [CO] flag.

CO is used to set cookies in htaccess when a specific RewriteRule or the rule containing “CO” flag matches.

In this article , I will show you how we can set cookies when a specific http host (domain) is requested.

Set cookie for specific host header

The solution being provided here is useful if you have multiple domains pointing to the same document root and you want to set cookies for a specific one.

Consider the following example :
This sets a cookie with the following name and value :

cookie name : mydomain
Value : example.com .
The cookie is set only if the rule matches. The rule matches if the condition is met. Here we are using the %{HTTP_HOST} condition to check the current domain name.

RewriteEngine On
#if the host = example.com
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
#run the rule and set cookies
RewriteRule .* - [CO=mydomain:example.com,L]

The rule above sets the cookie named mydomain and value example.com . You can access the cookie in your PHP script or use a rule in htaccess to check the cookie value. The rule above is not generic ,if you don’t want to set the cookie value manually , you can use the following rule instead as it sets the value of cookie automatically from the host condition

RewriteEngine On
#if the host = example.com
RewriteCond %{HTTP_HOST} ^(example.com)$ [NC]
#run the rule and set cookies
RewriteRule .* - [CO=mydomain:%1,L]

The rule examples above set the cookie successfully but there is still one important thing missing in the both examples. We forgot to set the cookie expire time or how long the cookie will survive. We need to add the validity argument to our code . The default cookie expire time is 0 which means the cookie will expire as soon as the browser window is closed.

You can set cookies expire time in minutes starting from 1. To set the cookie validity upto 1 hour we can use 60 as the validity argument.

RewriteRule .* - [CO=mydomain:%1,60,L]

Related article : How to set cookies with mod_rewrite .

Categories
Apache mod-rewrite and htaccess related Articles

Redirect website visitors to maintenance page with htaccess

This article explains how to redirect website traffic to one single page named maintenance.php using RewriteRule in htaccess file .
With htaccess you can forward your all site traffic to one page when your site goes in maintenance mode or when you are working on your website.

Forward all site traffic to one page with htaccess

To redirect your site traffic to one page, you can use the code below in your htaccess file.

RewriteEngine on
#Redirect site traffic to maintenance.php
#Excude the destination file
RewriteCond %{REQUEST_URI} !/maintenance\.php [NC]
RewriteRule .* /maintenance.php [R,L]

This will redirect any calls to your website to /maintenance.php file. We excluded the destination file in our code because it could cause an infinite loop error if not excluded in RewriteCond .In simple words the condition above says “Do not redirect maintenance.php To itself

R in the code above represents a Temporary Redirect with 302 status code. You can not use a permanent redirect or R=301 here because using a permanent redirect status can conflict with your site SEO.

The following is the shorter version of the code above.

RewriteEngine On

RewriteRule !maintenance\.php /maintenance.php [R,L]

As you can see , we removed the RewriteCond and excluded the destination path in the pattern of the Rule.

The rules above do the trick but if you are using local css and js files on your maintenance.php page, then your page might look without style and script as the rule redirects all calls to one page including css and js. To fix this issue you will need to exclude css and js files from the rule. To exclude these files , you can use RewriteCond directive or you can also exclude them in the rule’s pattern .

RewriteEngine on
#Redirect site traffic to maintenance.php
#Excude the destination file
RewriteCond %{REQUEST_URI} !/maintenance\.php [NC]
#Excude the css files
RewriteCond %{REQUEST_URI} !\.css [NC]
#Excude the js files
RewriteCond %{REQUEST_URI} !\.js [NC]
RewriteRule .* /maintenance.php [R,L]

It’s that simple!
I hope this article was helpful to you. Thank you so much for your time.

Categories
Apache mod-rewrite and htaccess related Articles

How to redirect IP hostname address to domain with .htaccess?

This article explains how to redirect an IP hostname to domain name using a RewriteRule directive in htaccess file.
Every domain name on the internet has an unique IP address assigned to it that connects the domain to internet.
If your website is accessible with both an IP address like (192.66.77) and domain name (example.com) then, in order to maintain the SEO , its important that you either redirect your domain to ip address or the IP address to domain.

URL redirection from domain name to IP address is uncommon as nobody will want the IP address to appear on their browser address bar as it might be hard for your visitors to remember it. Domain name on the other hand is easier to remember and type.

Table of contents

IP address to domain name redirection with htaccess

With an .htaccess file you can easily redirect your domain ip address to domain name.
You can simply use a RewriteRule for this purpose.

The rule bellow 301 redirects domain IP address to domain name.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^192\.1.55.88$
RewriteRule (.*) https://domainname.com/$1 [L,R=301,NE]

Explainations :

The rule above will match any http_host string that looks something like 192.1.55.88 . In this example , it matches the http_host ip address and if the match if found then the RewriteRule line is read. The rule redirects the ip host domain to domainname .
In simple words the code above will redirect any request from 192.1.55.88/foobr to domainname.com/foobar .
The R=301 in the rule above represents a permanent redirection with 301 status code . The R=301 is important here as it tells search engines to update the results with a new domain.

A solution for Apache 2.4 users

If your Apache version is 2.4 or above you can also use Redirect with IF directive that’s supported on Apache 2.4 or higher.

The following should work on Apache 2.4* :

RewriteEngine On

 <If "%{HTTP_HOST} == '158.1.88.99'">
 RedirectMatch 301 ^/(.*)$ https://example.com/$1
 </If>

Related :

.htaccess tutorial for mod_rewrite beginners .

Categories
Apache mod-rewrite and htaccess related Articles

Change uppercase URI to lowercase with mod_rewrite (.htaccess)

htaccess uppercase to lowercase

This article explains how to change an uppercase URI string to lowercase with mod_rewrite in an .htaccess file.
With htaccess you can easily convert upper-case characters in URL path to lower-case.
With just a few modifications and by adding a few lines of code you can redirect all of your Upper-case paths to lower-case to make the URL look nice with lower-case characters.
On this article we will provide you a 100% working solution that can just be copied and pasted.

Htaccess redirect uppercase characters in URL path to lowercase

A URL path with upper-case (capital latters) looks something like the following :

/PATH

And a path with lower-case characters looks something as shown below :
/PATH

Assuming your server has the following URL format :

https://example.com/THIS_PATH

You want to redirect URLs like this to its lower-case version

https://example.com/this_path

Here is the RewriteRule you can use in your htaccess to achieve this behaviour :


RewriteEngine on
RewriteCond expr "tolower(%{REQUEST_URI}) =~ m#(.+)/?$#"
RewriteRule [A-Z] %1 [R=301,L]

The rule above searches and converts all Capital letters in URL path string to small letter version. The location where you will put this in an htaccess file is important. If you put this at the bottom or before other rules/directives then it will not be read by server. You will need to put this at the top in your htaccess file.
I hope this article was helpful. Thanks for reading it.

Categories
Apache mod-rewrite and htaccess related Articles

How to disable directory listing/ directory browsing on Apache server

This article explains how to prevent or block directory listing on Apache web server using an htaccess and server.config files.

What is directory listing or directory browsing

When you request an existent directory on Apache an index file is served but if your directory doesn’t have an index file then Apache shows a list of files and folders. This is called directory listing .
The listing looks something like the following screenshot on Linux

Apache directory listing
By default Apache server shows an index file if it exists in the requested directory but if it doesn’t then the listing of all files and folders is shown.

An index file is the file that has a name starting with index . For example index.html , index.php etc.
If your folder doesn’t have an index file and you want to prevent the listing of files/folders then there are multiple ways to achieve this using a few lines of code in htaccess and server configuration file.
If you don’t have access to the main configuration file then you can use your htaccess. The solutions I am going to provide here work on both contexts.

Prevent directory listing on Apache web server using htaccess

Solution #1

The solution #1 is really simple. If you want to show a 403 error when your directory URL is accessed , you can just put the following line in your htaccess :

Options -Indexes

This two words line does the magic. It tells Apache to show a 403 forbidden error to clients when they request an existent directory . There are also some other ways to handle your direct directory access. See the examples below in the next section.

Block directory listing and set a specific file as index

Solution #2

To prevent directory listing on your server by setting a custom index file, you can use DirectoryIndex directive. This is one of the simplest and the easiest way to hide your files and folders . This directive is part of Apache directory module a module that is especially designed for directories on Apache.
I prefer this solution because it’s very easy to implement and just a single line of code can do the magic.
This directive is available for use in htaccess and server configuration. Since the directory uses same syntax on both contexts , I will show you an htaccess example here.

The following is the line you can use or update your htaccess with :

DirectoryIndex file.php

One liner.. very simple!
The line above instructs your server to show contents of file.php when a browser requests /directory/ .

file.php can be any file of your choice that you want to set as directory index.

An invisible redirection of URLs from /directory/ to file.php is performed by DirectoryIndex . By invisible here I mean you won’t be able to see the URL change in your web browser so the requested URL path /directory/ will show you the contents from file.php .

If you want the URL path to change from /directory/ to /directory/file.php then you can use DirectoryIndex Redirect along with the DirectoryIndex . This directive tells web server to issue an external redirect to index file when a directory is requested.

DirectoryIndexRedirect On

Use it along with DirectoryIndex

DirectoryIndex file.php
DirectoryIndexRedirect on

Note :DirectoryIndexRedirect On issues a temporary redirect from /directory/ to /directory/file.php with a 302 status code which is the default redirect http status code . To make the redirection permanent you can any of the following formats :

With 301 redirect status :

DirectoryIndexRedirect 301

With permanent status :

DirectoryIndexRedirect Permanent

Prevent directory listing/browsing with htaccess

Solution #3

You can also disable directory browsing by using RewriteRule directive in your htaccess file.

Here is the rule you can use in your htaccess :

RewriteEngine on
RewriteRule ^$ /file.php [L]

This works same as the DirectoryIndex method I explained above. This rewrites /directory/ to /file.php .

The most important thing to note here is the pattern ^$ .
In regular expression the pattern ^$ is used to check an empty string and in RewriteRule we use this to match against the current directory or the directory the htaccess file is located in.

For example if your htaccess is located in root then the pattern ^$ is used to match / and the same pattern is used if your htaccess is located in subfolder and you want to match that folder.

See the examples below .

/.htaccess

DirectoryIndex demo.php
DirectoryIndexRedirect 301
RewriteEngine on

This serves the demo.php file when the root directory “/” is direct accessed.

/subfolder/.htaccess

DirectoryIndex demo.php
DirectoryIndexRedirect 301
RewriteEngine on

If the code above is placed in htaccess in subfolder , then a request for /subfolder/ will show you demo.php file instead of showing directory listing.

Block directory listing/browsing using RedirectMatch

Solution #4

It is also possible to show a 403 forbidden error when someone tries to access your directory.

This method is not SEO friendly so I won’t recommend you to use it but if you really want to block direct access to your directories then you can use this.
To prevent directory browsing and display a 403 error ,you can use one of the following methods in your htaccess :

Block direct access to folders using RedirectMatch : This shows a 403 forbidden error when your directory is requested :

RedirectMatch 403 ^/folder/?$

Just replace folder with the name of the folder you want to show a 403 error. For the root folder you can use ^/$ . This does not affect files and subfolders.

Block direct access to folders using RewriteRule : This shows a 403 forbidden error when your directory direct accessed :

RewriteEngine on
RewriteRule ^folder$ - [R=403,L]

For the root folder or the folder your htaccess is located in you can use this pattern ^$ .

I hope this article was helpful . Thank you much for reading it.

Related : Htaccess tutorial for beginners.

Categories
Apache mod-rewrite and htaccess related Articles

Two ways to manipulate URL query strings using RewriteRule in htaccess

Query strings are part of URL that usually appear at the end or before fregment.
A typical query string looks something like the following :

?q=foo&bar=123

Query string in URL starts with a question mark and it contains query key and value parameters.
In the Query String above , q is a key and the foo is its value. Multiple Query key values are separated by an & character.
In this article I am going to show you some useful ways to manipulate query strings using RewriteRule directive. If you want to learn how to match against URL query strings using RewriteRule then you can read further because this post is written especially for URL rewriting beginners. I will show you two working mod_rewrite tricks to manage URL query strings.

Apache mod_rewrite has predefined methods to work with URL query strings

Mod_rewrite beginners often find it complicated to manage or Redirect URL query strings but in fact it’s not that hard. Mod_rewrite has predefined variables to work with it.
The following are the two variables we can use use to manipulate URL query strings :

  • %{QUERY_STRING}
  • %{THE_REQUEST}


%{QUERY_STRING}
is used to match against URL query string. You can use this variable to match against URL query strings.

The following is an an example of how we can test URL query string using RewriteCond directive :

RewriteCond %{QUERY_STRING} ^q=foo&bar=123$ [NC]

The condition above checks a static URL query string that looks something like the followin
?q=foo&bar=123 .
You can use Regular expressions to check query string values dynamically , the following is an example :

RewriteCond %{QUERY_STRING} ^q=.+&bar=.+$ [NC]

The example above matches any values in the query string.


%{THE_REQUEST}
represents the full URL requested by a web browser, you can also use this variable to check URL query string.
If we have the following URL :

example.com/file.php?q=foo
Then we can use the following condition to make sure the URL has the specified Query String

RewriteCond %{THE_REQUEST} \?q=foo\s [NC]

The “\s at the end of the condition pattern above matches a space char and it’s important to use when you are using this variable in RewriteCond as it works like a string boundary.

Redirect URL with Query String

Now you know that we can check query string in two ways on Apache mod_rewrite.
URL redirection with query string is easy .
Suppose we want to redirect our URL with a specific query string to another URL ,

We will learn to redirect :
example.com/file.php?q=foo&n=123
to a different URL , that looks something like :
example.com/demo.php
You can see the second URL is clean and it has no query string , we will use the following rule in our htaccess file for this redirection :

RewriteEngine on
RewriteCond %{QUERY_STRING} ^q=foo&n=123$ [NC]
RewriteRule ^file\.php$ https://example.com/demo.php? [R,L]

One important thing to take note of in the rule above is ? that is at the end of the target URL. This empty question mark is important otherwise the old query string will get appended to the target URL.

The following is the same redirection rule with %{THE_REQUEST}

RewriteEngine on
RewriteCond %{THE_REQUEST} \?q=foo&n=123\s [NC]
RewriteRule ^file\.php$ https://example.com/demo.php? [R,L]

Related articles