Categories
Apache mod-rewrite and htaccess related Articles htaccess url-rewrewriting

How RewriteBase works with RewriteRule in an htaccess file

How RewriteBase works in htaccess

RewriteBase directive sets a base path for all relative links in RewriteRules.
In this article I will tell you how RewriteBase works and when we should and when we shouldn’t use it in our htaccess file.

How RewriteBase works in htaccess

This directive appends a custom path to all relative rewrite substitution strings in an htaccess file.
RewriteBase is part of Apache mod-rewrite a module provided by Apache for rewriting URLs.

It works with mod-rewrite directives such as RewriteRule.
Let’s see some real world htaccess rules to better understand how it actually works .
The following rule in a /subfolder/. htaccess does not contain a RewriteBase and the substitution string is using a relative path starting without /


RewriteEngine on
RewriteRule ^foobar$ file.php [R]

We created the above rule to redirect /subfolder/foobar to /subfolder/file.php but unfortunately this will redirect you to the file.php located inside root folder.
This is because “file.php” in the rule’s substitution string is pointing to root directory .
It’s looking for the file in your root directory so your redirected URL path will look something like “/file.php” instead of “/subfolder/file.php” .
You can fix this either by using a RewriteBase or using absolute file path in your rule’s target.
RewriteBase


RewriteEngine on
RewriteBase /subfolder/
RewriteRule ^foobar$ file.php [R]

The rule above will now correctly point your URL to “/subfolder/file.php” .
The “/subfolder/” perfix is automatically copied from the RewriteBase to the relative target path in the rule above.
You don’t need to use RewriteBase if you are using an absolute path pointing to the current directory. The following is an example of that :


RewriteEngine on
RewriteRule ^foobar$ /subfolder/file.php [R]

Since the rewrite destination in the rule above is using an absolute path pointing to the subfolder , this will redirect your URL to the correct location. You don’t need to use RewriteBase here as the base path isn’t copied to absolute substitute strings.


If you are new to htaccess , and want to learn some basics of mod-rewrite ,You can check out this mod-rewrite tutorial for beginners .

Categories
Apache mod-rewrite and htaccess related Articles htaccess url-rewrewriting

Mod rewrite R vs R=301 flag which one should you use for URL redirection

R vs R=301 htaccess

Both R and R=301 flags are used to redirect URLs using RewriteRule directive. Some new mod-rewrite users often get confused with whether they should use R or R=301 in their RewriteRule.

In this post I will explain both flags and when to use these flags in your Rule.

R flag in RewriteRule

R represents a temporary redirection. R is same as R=302 so you can use one of these two forms of the flag to redirect your URL with temporary redirect status code. Both R and R=302 issue a 302 redirect status to clients. 302 is a temporary redirect.

R=301 flag in RewriteRules

R=301 is a permanent redirection flag. It uses 301 status to redirect the URL from one location to the other.

When to use R

You should this flag for testing purposes only. Since it’s a 302 temporary redirect , if you use this on a real site URL then you can get into trouble of loosing your search engine rank. As search engines do not index temporary redirects.
The benefit of using temporary redirect flag while testing RewriteRules is that it isn’t cached by your web browser. You can test your RewriteRule freely without worrying about browser cache.
You can also use R flag when you want to redirect your site URL to a different URL or path for some time. This redirection won’t be noticed by search engines.

When to use R=301 vs R in RewriteRules

R=301 is a permanent redirect flag. It is cached by your web browser and indexed by a search engine. You can’t use it while testing your RewriteRule code as it’s cacheable by browsers. Once you have verified your rules are working you can then change your R to R=301 . It’s recommended to do so unless you are really doing a temporary redirection.
A 301 redirect tells search engines that the URL has changed . This tells search engines to update their databases with a new URL.
In general , if you are using a RewriteRule just to test it on your server then you must avoid using R=301 as it can be cached and remains in the browser memory until you clear it.

Categories
Apache mod-rewrite and htaccess related Articles htaccess

How to set http cookies via mod-rewrite in htaccess ?

htaccess set cookies

Hello! In this post I will show you how we set an http cookie using a RewriteRule directive in an htaccess or server.config file.
I saw many unanswered and confusing posts on StackOverflow and on other sites so I thought It would be worth writing a post that can help peope who are searching the similar solution on the internet for help.

Setting cookies using mod rewrite

With RewriteRule directive you can set http cookies the same way as you rewrite URLs.
Cookies are set using [CO] Cookie flag of apache mod-rewrite. The cookies you set via RewriteRule can also be accessed by client or server scripting languages like PHP and JS.
Mod rewrite cookies are mainy used for rewriting requests based on http cookie header.
You often set a mod rewrite cookie to rewrite/direct URLs if a specific cookie exists.
Let’s start with a basic example first:


RewriteEngine On
RewriteRule (.*) - [CO=user:john]

The rewrite rule above will set cookie named user and as you can see we manually assigned value john to it.
Explanation :

  • The first line “RewriteEngine on” tells server to turn on the engine for rewriting URLs. This setting is disabled by default so you must use this line ones at the top of RewriteRules in htaccess or server.config.
  • The second line is that does the Rewrite mazic and sets the cookie whenever you request an URI from server.
    RewriteRule (.*) – [CO=user:john]” matches any incoming URIs as the pattern (.*) means to match anything. The hyphen in the Rule’s destination above lets your URLs pass through unchanged meaning that when you request “/file.php” only the CO flag will be applied to the URL and there will not be any change in the URL. In most cases when setting cookies by RewriteRule you use as the destination path because we don’t want to rewrite the urls we just want to set a cookie for URLs. “[CO=user:john]” sets user cookie with value john. You can also use a dynamic value using regex match “$1” or “%1” .

Setting cookies for specific URIs

In the basic example above we learned how to set cookies when any URL passes through RewriteRule. You can also set cookies for a specific URI. For example to set cookies only for a single path or file ie /this-file.php you can restrict the pattern of RewriteRule to match only this URI. You just need to write a regular expression pattern to match that particular path.

RewriteEngine On
RewriteRule ^this-file.php$ - [CO=user:john]

This will set the cookie only when you request is for /this-file.php . This rule example might fail on server.config, add a leading slash in the pattern ie: ^/this-file.php$ to use this in a server.config file.

Checking cookies using mod-rewrite

We use RewriteCond directive to check whether a cookie is set or not set. We can also check what value the cookie holds.
The following is a basic example of checking whether a cookie is set :

RewriteCond %{HTTP_COOKIE} !^$

In the example above we want to make sure our cookie is set or not empty (!^$) . You can use a RewriteRule bellow this condition so it executes if the condition is met.
In the example bellow, we will redirect /this-file.php to root / if our user cookie is not set.

RewriteEngine on
RewriteCond %{HTTP_COOKIE} !user
RewriteRule ^this-file.php$ / [R,L]

Another mod rewrite example

RewriteEngine on
RewriteCond %{HTTP_COOKIE} ^user=john
RewriteRule ^this-file.php$ / [R,L]

The rule above will redirect /this-file.php to / if the cookie user and value john is not set.

Setting cookie user if it doesn’t exist

You can set a specific cookies if it doesn’t exist using the following RewriteRule:

RewriteEngine on
RewriteCond %{HTTP_COOKIE} !^user=john
RewriteRule ^this-file.php$ - [CO=user:john,L]

In the example above we first check the HTTP_COOKIE header to ensure that the cookie “user=john” is notset and then we set it via RewriteRule.

Setting cookies for a specific domain

By default, mod-rewrite cookies are set for all domains that point to the same document root. You can add an optional perameter domain to the CO flag. To set cookies only for www.example.com host you will use something like the following:

RewriteEngine on
RewriteCond %{HTTP_COOKIE} !^user=john
RewriteRule ^this-file.php$ - [CO=user:john:www.example.com,L]

Setting cookies with Lifetime

By default mod-rewrite cookies are set for current session only which means when the browser window is closed the cookies also get get destroyed. You can add a lifetime perameter in minutes to CO flag to customise cookies validity.

RewriteEngine on
RewriteRule ^this-file.php$ - [CO=user:john:www.example.com:10,L]

In the example above the user cookie is available only on www.example.com host and it expires after 10 minutes.

Cookies for specific path only

You can make the cookies available for a specific path only. By default mod-rewrite cookies are set for / which means the entire site. To set a specific path you may use :

RewriteEngine on
RewriteRule ^this-file.php$ - [CO=user:john:www.example.com,L]

Setting cookies expire time

You can set how long an http cookie will survive, by default mod-rewrite cookies are set for current browser session only and deleted when we close the browser window. You can add a time perameter to CO flag to extend the cookie validity . Time value is set in minutes.

RewriteEngine on
RewriteRule ^this-file.php$ - [CO=user:john:www.example.com:10,L]

This will set user cookie on www.example.com host with a validity of 10 minutes.

Categories
Apache mod-rewrite and htaccess related Articles

How to remove traling slashes from URLs using RewriteRule | URL Rewriting Tips

htaccess remove trailing slash

A slash , / character, that appears at the end of URL path is called a traling slash.
A typical URL with traling slash looks something like the following:

https://example.com/path/

A traling slash at the end of an existing directory prevents directory listing so its important to keep it on a directory path. Mod-dir a directory module automatically adds a slash at the end when you request a directory without a traling slash. Mod-dir does so to keep your directory secure.

You can remove traling slashes from other URLs on your server that do not point to existent folder(s) . I will show you how you can do this using RewriteRule directive.

Remove traling slash from URLs using RewriteRule

You can remove traling slashes from your URLs using RewriteRule directive either in server.config or in an htaccess file. The following example works in both context :


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

The rule above will redirect a URL path with traling slash ie. /path/ to /path .
The RewriteCond in the rule above makes sure the rule doesn’t redirect your existing directories.

Categories
Apache mod-rewrite and htaccess related Articles htaccess url-rewriting

Rewrite /username/ to /user.php?user=username with RewriteRule htaccess |URL Rewriting Tips

htaccess rewrite user urls

In this post post I will show you how to shorten a user URL on Apache server by htaccess.

Assuming you have a long user URL that looks something like the following:

/user.php?username=foobar

And you want to shorten this URL to :

/foobar

The shorter version is easier to remember ,type and search engine friendly.
You can easily do this using RewriteRule in htaccess.
You just need to rewrite the “short/new version” to the “old/longer one” . This can be done very easily with just a single RewriteRule line.

The following RewriteRule will rewrite /foobar to /user.php?user=foobar


RewriteEngine on
RewriteRule ^foobar /user.php?user=foobar [L]

The rule applies only to a single URL path, to re5the user URL dynamically you could use :


RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+) /user.php?user=$1 [L]

This RewriteRule rewrites any user path that matches the pattern (.*). The RewriteConds in the rule above are important as it prevents your existing files and folders from being rewritten.

With the above rule you will be able to access your old long user URL using a new short URL. So instead of going to /user.php?user=username you can simply go to /username .

Categories
Apache mod-rewrite and htaccess related Articles htaccess

Mod-rewrite NC (NoCase) flag | URL Rewriting Tips

What is NC in mod-rewite?

How NC flag works in htaccess

NC stands for NoCase and is a URL rewriting flag used on Apache server.
We use NC to rewrite URLs in a case insensitive manner.
With NC flag set in RewriteRule you can use both upper-case and lower-case in URL path matching the rule’s pattern pattern.

If NC flag is present in RewriteRule then pattern of that rule can match URL path ignoring the character case.

How NC works in RewriteRule

Let’s see an htaccess example to better understand how this flag actually works :
Rule without NC


RewriteEngine on

RewriteRule ^foo$ /demo.php [L]

The above rule rewrites /foo to /foo.php but it will not work if you type /Foo because our URI has upper-case “F”. If you try a case-insensitive URI you will get a 404 not found error.

Rule with NC


RewriteEngine on

RewriteRule ^foo$ /demo.php [L]

The example above works for both types of URIs (upper-case and lower-case) .

When to use/not use NC flag in RewriteRule

If you are using a static pattern in RewriteRule then you need to use NC to accept any case characters in input URI.
In the following example NC is important :


RewriteRule ^File.php$ /file2.php [NC]

This example will also match /file.php because the NoCase flag is present there to avoid case-sensitivity.

You do not need to use NC flag when you are using a regex pattern that accepts any characters ie (.*)$ .

RewriteRule ^(.*)$ /file2.php

NC is not needed in the above example because the regex pattern matches all URI characters.


I Hope you enjoyed reading this Post. Thans for your time.

Categories
Apache mod-rewrite and htaccess related Articles htaccess

Reditect domain using proxy P flag in htaccess

Apache Proxy module

Reditect domain to another domain with P flag htaccess

“Apache Proxy module” also known as mod-proxy is a URL rewriting module provided by Apache. This module enables URL rewriting between domains hosted on two different servers.
With mod-proxy enabled , you can redirect your domain to an external domain without changing the URL in browser.

You can proxy requests from your domain to a domain on remote host with this module. You can learn more about mod-proxy on the official Apache guide which is on the following URL https://httpd.apache.org/docs/2.4/mod/mod_proxy.html

This module doesn’t come pre-installed which means you must first enable it from the server config in order to use it.

How to use mod-proxy?

You can use proxy module to rewrite external URLs. If this module is active on your server then you can use mod-rewite P flag which stands for “Proxy” .
P flag can be used in htaccess, server.config and virtual host context.
With P flag you can rewrite your URLs to URLs on another domain which is being hosted on a remote server.
For example:
You can rewrite

http://domain1.com/path

To

http://domain2.com/path

P flag will proxy the request from domain1 to domain2 without changing the URL.

Using P flag in htaccess

P flag can be used in htaccess or other contexts. Here I will show you an htaccess example so you can understand how it actually works.



RewriteEngine on

RewriteRule ^foobar http://example.com/foobar [P]

To see how it works, put the above code in your /.htaccess and visit yoursite.com/foobar .
The rule will internally map your URL to example.com/foobar showing you the contents of the example.com domain on the same URL.
In case the rule returns a 500 server error then one possible might be that the module isn’t enabled.

How to install mod-proxy on Apache server

To install the proxy module
Go to the source directory of the Apache installation

cd /usr/src/httpd-2.2.24

Replace the path with where you downloaded the Apache installation.
Reconfigure the existing apache configuring appending the mod_proxy lines
./config-nice –enable-proxy=shared Rebuild Apache:
make
Install the new Apache
make install
Once you have done that you will want to edit the Apache Configuration to load the modules


vim /etc/httpd/conf/httpd.conf
Add the following modules and save the file

LoadModule proxy_module lib/apache/mod_proxy.so
LoadModule proxy_http_module lib/apache/mod_proxy_http.so
LoadModule proxy_balancer_module lib/apache/mod_proxy_balancer.so
LoadModule proxy_connect_module lib/apache/mod_proxy_connect.so
LoadModule proxy_ftp_module lib/apache/mod_proxy_ftp.so
LoadModule proxy_scgi_module lib/apache/mod_proxy_scgi.so
LoadModule proxy_ajp_module lib/apache/mod_proxy_ajp.so

Restart Apache to load them using service httpd restart
In case you don’t have access to the main configuration file (this usually happens if you are on a shared hosting server) then you can ask your hosting provider to enable the module.

Categories
Apache mod-rewrite and htaccess related Articles

htaccess redirect users based on browser language | URL Rewriting Tips

Redirect users based on browser language

htaccess redirect visitors based on browser language

If you have a multilingual website that is available to users in the language that they understand, you can set an automatic redirect with htaccess that will redirect your users to the language version their browser is in.

For example a user visiting your site from Spain if their browser language is “es” then RewriteRule can automatically redirect the user to “es” version of your website.
With RewriteRule this can be done by checking the %{HTTP:Accept-Language} variable. This variable automatically defects browser default language.


%{HTTP:Accept-Language} is a pre-defined mod-rewite server variable and used for detecting browser language in mod-rewite.
The following is a basic example of browser language detection. The rule will redirect your website hompage to example.com/en if the rule’s condition is met.

RewriteEngine on
RewriteCond %{HTTP:Accept-Language} en [NC]
RewriteRule ^/?$ http://example.com/en [L,R]

This RewriteRule will redirect / the hompage of your website to example.com/en if the RewriteCondition RewriteCond %{HTTP:Accept-Language} en [NC] is met. The condition checks the browser language and if it finds en in the language string then the rule is applied.
This rule will not get applied to browsers with language other then “en”.

Detect multiple browser languages with RewriteRule

To detuct multiple languages and redirect based on the deducted language string you can use the following:

RewriteEngine on
RewriteCond %{HTTP:Accept-Language} (en|es|fr) [NC]
RewriteRule ^/?$ http://example.com/%1 [L,R]

The above rule works for 3 languages “en ,es and fr” . The rule automatically defects browser languages and redirects the hompage to example.com with the available lang path.

Categories
Apache mod-rewrite and htaccess related Articles htaccess

A simple htaccess rule to block web crawlers and Http user agents | URL Rewriting Tips

What is a web crawler?

A Web crawler, also called a spider or spiderbot and often shortened to crawler, is a type of Internet bot that systematically browses the World Wide Web, typically for the purpose of Web indexing (web spidering).
Search engines like google , yahoo use web crawling software that automatically reaches out to domains (that allow indexing) on world wide web to index them .

How to block web crawlers on my site?

If you do not want your domain to be available in search results or you want to keep your domain away from web indexing, then you can block user agents that visit your website for the purpose or crawling.

One of the quickest solutions to block web crawlers is URL rewriting. You can add a RewriteRule to your htaccess to do this.

Block “google web crawler” with RewriteRule

To block “google web crawler” you can use the following rule :


RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} googlebot [NC]
RewriteRule .* - [F]

If you add this code to your htaccess in root folder then this will deny all requests to google web crawlers. Google bot will get a forbidden 403 error if it visits any page on your domain.

Block multiple web crawlers using RewriteRule

You can block more then one crawler bots using one single RewriteRule.


RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} googlebot|yahoo|bing [NC]
RewriteRule .* - [F]

The above rule will block Google , Yahoo and Bing search bots from your site. To add more bots just separate them using a Pipe char | in the RewriteCond.

Categories
Apache mod-rewrite and htaccess related Articles htaccess

Redirect 404 URIs to a different domain with htaccess | URL Rewriting Tips

Redirect 404 URIs to a different domain with htaccess

The following rule will redirect all 404 URIs from your site to http://example.com


RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .+ http://example.com/ [L,R]

You can just copy and paste this rule to your htaccess in document root folder.
This rule will only redirect 404 URIs on your site without affecting your existing files/folders.