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

How mod-rewrite L and END flags work in htaccess

L and END flags in htaccess

In this article I will give you a quick overview of mod-rewrite L and END flags.
I will show you (with examples) how these two flags work and what’s the difference between L vs END .

What is L flag and how it actually works in htaccess

L is the most used flag in RewriteRule in htaccess. You can see it at the end of all RewriteRules in an htaccess file.
L means Last in RewriteRule. This flag indicates that the rule is last. If the rule has matched use it without looking in other RewriteRules.
L is the most commonly used flag in RewriteRule. But a few people know this that “L” actually has no effect in RewriteRule.
Your rule will work same even without it but using it at the end of every RewriteRule is a good practice as it makes your rule line look complete.

The official Apache mod-rewrite manual says that “Using L at the end of the rule tells server not to match other rules if the current one has matches the request successfully.
The following is an example according to the manual :

RewriteRule ^foo$ /demo.php [L]
RewtiteRule (.*) /somefile.php [L]

The L has been used in the Rules above.
The first rule is for a particular URL path /foo and the second one is for all incoming paths.

Following the L flag explaination from manual you would think , the first rule above will match /foo and rewrite it to /demo.php . Done?

No!!
If you use the rules above in an htaccess file then your server will return an infinite loop error if you request /foo .
Since The second rule has a catch-all pattern, it matches the request from the first rule. L doesn’t work here as it’s just like a place holder.

Related post :
Mod-rewrite tutorial for beginners

Htaccess file has to load multiple times on server in order to process the request, so in the case above , if you type /foo the htaccess file loads and the first rule is triggered.
Then in order to process the rewrite destination file demo.php htaccess loads again. The second rule matches the demo.php and rewrites it to somefile.php . The internal Rewriting process doesn’t stop here.
To process the destination file somefile.php the htaccess loads again and the the pattern (.*) matches rewriting the somefile.php to itsef.
You can see the L the “last” flag no effect at all here. Its just serving its purpose as a placeholder here.

L flag stands for “Last” but it does not do its job in RewriteRule.

What is END flag used for in RewriteRule?

END is the most powerful flag in mod-rewrite.
END flag does what the L doesn’t

END flag ends all the internal rewriting process immideatly.

END flag available for use since Aoache 2.4 .You can’t use it on lower versions of Apache server . Using it on a lower version will result in a 500 server error.

In the following Rules we are using END instead of L .

RewriteRule ^foo$ /demo.php [END]
RewtiteRule (.*) /somefile.php [END]

Now if your request /foo the rewriting will be processed smoothly without causing any error.
The END flag in the rule above terminates all the internal rewriting process as soon as the rule is matched and the destination file is served. This doesn’t tell the server to load htaccess again.

END flag has no effect with external redirection rules

Since END is made for internal URL Rewriting , You can use it with RewriteRules that rewrites the request internally.
Using is with a RewriteRule that use R flag or the full URL in destination has no effect at all. Because the flag END is for internal Rewriting.

Categories
apache Apache mod-rewrite and htaccess related Articles htaccess mod-rewrite

Prevent hotlinking using htaccess

htaccess block hotlinking

Hotlink protection using htaccess

One of the most beneficial use of htaccess is to prevent hotlinking of images , videos and other documents on your website.

You can use htaccess to prevent hotlinking of your media and other documents.

What is hotlinking?

It means to display an image on a website by linking to the website hosting the image.
For example : An image “cat.jpg” hosted on server1 can be displayed on “server2” using src link to the server1 .
This uses the Server1 resources to load and display the image.

Why you should prevent hotlinking ?

Hotlinking consumes your server resource like bandwidth which can slow down your server performance.

If your hosting server provides limited bandwidth then “hotlink blocking” is useful for you as you do not want your server to be down by external http requests.

RewriteRule to prevent hotlinking

Many people who don’t want their site to be hotlinked use htaccess.

It’s easy to stop hotlinking using an htaccess file.

The following is a basic Rule to prevent image hotlinking on your website :

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://yoursite.com [NC]
RewriteRule .(jpg|png|gif)$ - [F]

This checks the “HTTP_REFRRER” domain string , if its not http://yoursite.com then any calls to jpg , png and gif files on your site will get a F 403 forbidden error.

Linking an image file on another server using your domain “http://yoursite.com” will show a forbidden error.
For example, <img src=”https://yoursite.com/image.jpg”> won’t load the image file on another server.

If yoursite.com is accessible by both https or www , then to prevent hotlinking you need to use a regex based pattern in RewriteRule to match both versions :

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http(s)://(www.)?yoursite.com [NC]
RewriteRule .(jpg|png|gif)$ - [F]

This will prevent hotlinking of image files on “https://www.yoursite.com” , “https://yoursite.com” and “http://yoursite.com” (with or without www) .

Keep in mind that, hotlink protection doesn’t mean your images won’t be indexed by search engines. Google will still index your images as it doesn’t use http referer header to find and index files.
Your images will still appear on search results but can’t be used on another website by linking to your server.

Stop hotlinking of video files.

You can use the following rule to stop hotlinking of video files on your server.

I have just added one extension in the rule . If you have more video extensions to stop hotlinking you can add them in the pattern using regex like this .(mp4|ext2|ext3)$ .

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^https?://(www.)?yoursite.com [NC]
RewriteRule .mp4$ - [F]

This will set a hotlink protection for mp4 files on your server.

htaccess Allow/Deny hotlinking

By using the above rules you deny hotlinking to all external sites. If you want to allow access to a specific external site that can use your media files then use :

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^https?://(www.)?(example1.com|example2.com) [NC]
RewriteRule .(jpg|png|gif)$ - [F]

This will block image hotlinking for all sites except “example1.com” and “example2.com” . If the “example1.com” is hosting the image files then you can also hotlink those images on “example2.com” .

Display a static image for hotlinked requests

You can show a static image for hotlinking calls on your server using htaccess.
Instead of 403 error you can rewrite all hotlinking calls to an image file this will make it so that when someone tires to link your image on their website they will get the image instead of the one they intended to show.

This does use your bandwidth but this way you can reduce the number of hotlinking calls on your server.

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^https?://(www.)?yoursite.com [NC]
RewriteRule .(jpg|gif|png)$ /hotlink.png [L]

Hope this article was helpful.
Thanks for reading!

Categories
apache Apache mod-rewrite and htaccess related Articles htaccess mod-rewrite

convert a long URL into short using RewriteRule in htaccess

Shorten long URL with htaccess

URL rewriting on Apache server is one of the most easiest and convenient way to shorten a long URL to make it short and search engine friendly.
Apache server supports server.config and .htaccess files .

Not all web hosting providers allow you to access the main server.config file and in that case the only option to rewite URLs is with htaccess .

You can edit your htaccess file to add URL shortner rules into it.
In this post I will show you how to shorten a long PHP URL to short one by htaccess.

Shorten a long URL by htaccess

Suppose we have a user site that generates user URLs in the following format :

https://example.com/?user.php?user=john

As you can see our URL is long,hard to remember and not search engine friendly.

This type of URL can cause duplicate content issue on search engines.

Now look at the following URL :

https://example.com/users/john

Does it look short and nice?

Yes.. the second one makes sense as it’s short and search engine friendly.

To convert your original URL into this new URL format you will need to write a Rule in your htaccess that can map the new format to the old one .

RewriteRule to map /users/john

to

/user.php?user=john
:

RewriteEngine on
RewriteRule ^users/john$ /user.php?user=john [L]

Ok..so what the above rule does is it rewrites the requested URL path
/users/john to /user.php?user=john .

Pretty simple?

The rule tells your web server to make an internal redirection from new URL format to the old one and since the redirection is performed internally your browser won’t notice it and the typed URL won’t change in the browser address bar.

Now you can test your new URL format by going to the following URL :

https://example.com/users/john

Isn’t it interesting?

The rewiteRule I mentioned above applies only to a single user URL /user.php?user=john.

What if you have more the one user ? Would you need to write multiple rules to handle them?

No.

If your user.php path is dynamic, you can use a dynamic regex pattern.

The RewriteRule bellow applies to any user path.

RewriteEngine on
RewriteRule ^users/(.+)$ /user.php?user=$1 [L]

As you can ,we slightly modified the rule and replaced the static “UserName” with a dynamic catch-all regex capture group (.+) .

The regex capture group captures any character(s) after /users/ in the request path and saves the value in $1 variable.

With the rule above if you visit /users/foobar then the rule will dynamically rewite the path /users/foobar to /user.php?user=foobar .

Now that our user URL is short and SEO friendly, but there is still one major thing that can prevent the short URL from being indexed by search engines. Now you can visit the user.php URL either by going to /users/foobar or by typing the old format /user.php?u=foobar .
This will cause a duplicate contents issues on search engines as Two diffrent URL paths point to the same location.
To fix this, you can write a new rule that will 301 redirect your longer URL to the shorter one.

RewriteEngine on
#301 redirect /user.php?user=foobar to /users/foobar
RewriteCond %{THE_REQUEST} /user.php?user=([^s]+) [NC]
RewriteRule ^user.php$ /users/%1? [R=301,L]

Here is the complete rule to shorten the URL :

RewriteEngine on
#1 301 redirect /user.php?user=foobar to /users/foobar
RewriteCond %{THE_REQUEST} /user.php?user=([^s]+) [NC]
RewriteRule ^user.php$ /users/%1? [R=301,L]
#2 map /users/foobar to /user.php?user=foobar
RewriteRule ^users/(.+)$ /user.php?user=$1 [L]

Hope you enjoyed reading the post! Thank you so much.

Categories
apache htaccess mod-rewrite

RewriteRule vs Redirect directive runtime behavior explained with examples

Redirect vs RewriteRule runtime

What is RewriteRule

RewriteRule directive is used to rewite/redirect URLs on Apache server. To convert a longer URL path into shorter one we use RewriteRule directive which is part of Apache mod-rewite (Rewrite Module) .
The following is the basic syntax of RewriteRule directive:

RewriteRule newPath oldPath [flags]

Redirect directive

Redirect directive is part of Apache core module which is mainly used for URL redirection on Apache server. Redirect directive is used to redirect URL path from one location to the other for example /this to /that .

Syntax of Redirect directive:

Redirect  /newPath oldPath 

I often see users posting questions on stackoverflow about URL redirection. in their initial attempts to redirect the URLs they either try a mixture of RewriteRule and Redirect directives or misorder the directives which produces an unexpected result.

RewriteRule and Redirect are directives of two different apache modules. Although both the directives are used for URL redirection but due to their different run time behavior you can use them together in a single rule block.
RewriteRule directive takes precedence over Redirect directive. No matter where you place the Redirect if there is a RewriteRule directive with the same pattern as Redirect Apache server will check the RewriteRule first even if your Redirect line is at the top of your htaccess or server.config.

To better understand the runtime difference between these two directives, let’s see some real world code examples now .

RewriteRule vs Redirect

The main difference between these two directives is ther runtime behavior. Both directives run on different time. Apache server often reads RewriteRule first.

Here is a basic htaccess code example to better understand the behavior :

Redirect /demo.php /location.php
RewriteRule ^demo.php$ /location.php [L,R]

The both lines above does the same thing as they redirect /demo.php to /location.php . As you can see the RewriteRule directive is placed bellow the Redirect in the above code, you would expect the Redirect to trigger first but The apache server will read the RewriteRule line first as this directive takes precedence over Redirect.

Intermixing RewriteRule with Redirect

Some people who are new to URL rewriting world often mix RewriteRule with Redirect. They use both directives together in htaccess hoping that the redirect will work normally this way but it doesn’t. Why ? Because these two directives are part of two different apache modules.

Redirect /file.php /file1.php
RewriteRule ^file /file2.php [L,R]

In the above code we used Redirect directive to redirect /file.php to /file1.php and RewriteRule to redirect /file to /file2.php .

Since the pattern of above RewriteRule matches anything after file this will also match the /file.php request path so in the above code example our Redirect will never be triggered as the RewriteRule runs first and redirects any path starting with /file.

Categories
apache htaccess mod-rewrite

Can we redirect fragment/hash URLs using htaccess RewriteRule?

Redirect fregment URLs using htaccess

I often see users struggling with their RewriteRule to redirect fragment URLs.

Fragment is something that the server doesn’t receive meaning that a URL containing #path  can not be redirected using htaccess or any other server side redirection methods.

Fragment usually appers at the end of the URL and starts with a “#” character.

Anything that comes after # in URL is part of URL fragment.

A fregment is handled client side ( by web browser) and used as jump to navigation link in a web page. 

When  a fragment URL is typed in browser address bar your web browser makes it so that the page automatically  scrolls to the fragment href section on the requested page .

The following is an example  of fragment URL:

http://example.com/file.php#foobar

In the above URL , /file.php is URL path and #foobar is a fragment.

Your web server only receives the URL path  as request header string and the remaining part (#foobar) is trimmed or not sent. Since the fragment is manipulated client side , your webserver doesn’t get such URL segment and there is no way to handle it server side.
You can redirect fragment URLs using JavaScript or other client side redirect logic. In the last paragraph bellow I will show you how we redirect fragment URLs client-side  with some code examples.

Redirect to a Fragment URL using RewriteRule

It is quite possible to redirect your original URL path to a fragment URL . For example example.com/thispath can be redirected to example.com/#thispath using NE  and R (NoEscape and Redirect) flags in RewriteRule directive. 

But
example.com/#thispath can not be redirected to example.com/thispath because the requested URL contains # path and its is not manipulated server-side. 

You can’t redirect fragment using htaccess RewriteRule

As I already mentioned fragment is manipulated by web browser and not by server . All you can do to redirect your fragment URL is JavaScript redirect.  I often see users posting questions on stackoverflow regarding #path where they want to redirect fragment URLs to a custom path . For example /path/#foobar to /newpathWithoutFregment and the RewriteRule they try is something like :

RewriteRule ^path/#foobar /newpathWithoutFregment [R]

The rule above will never work because of the following two reasons :

  1. # is a special character in mod-rewite as it is used to add comments in RewriteRule.
  2. # is a fragment which is maintained by browser  and its not sent to the server.

The rewiteRule above won’t work even if you escape the # character as its not even sent to the server. 

The following Rewriterule works  perfectly fine

.

You can redirect your URL path to fragment using NE and R flag.

Here is a RewriteRule example to redirect /foobar to /#foobar :

RewriteRule ^foobar /#foobar [NE,R]

The above example works because here you are redirecting your NonFregmentPath to a FragmentPath. You type the path /foobar into your browser, your browser then sends the path to server , server receives the path , reads htaccess rules and then issues a Redirect (/foobar => /#foobar) to your webbrowser . And finally your web browser makes the hash redirection.

The NE flag is important in the rule above.  Without NE the # gets encoded to its hex value which may end up in an incorrect or not found path.

JavaScript based solution to redirect fragment URLs

Since JavaScript is a client scripting language and works on web browser, you can easily redirect your fragment URLs using JS window.location.assign() property . The following is a simple one liner code to redirect /#foobar to http://example.com/#foobar .

window.location.assign(“http://www.example.com/”+window.location.hash)

The window.location.hash() property returns the current page hash ie #foobar in this example.

You can learn more about JS location pproperties on the official Mozilla site here .

I hope the post was helpful. Thank you so much for reading.

Categories
apache htaccess mod-rewrite

Time based URL rewriting Apache htaccess

Time based URL rewriting on Apache

With mod-rewite you can rewite or redirect your URLs based on server date and time logic. You can redirect your visitors to a specific page or URL destination using this date/time logic.
In this post, we will learn how to apply date/time conditions to RewriteRule directive with some code examples of basic to advance Time based URLrewriting.

Let’s first have a look at available mod-rewite date/time variables

Mod-rewite date and time variables

The following are the pre-defined apache mod-rewite variables to work with server date and time . The date and time Alpanumbric values these variables contain depend on the timezone set on your server.

You can set server timezone using server.config file.

%{TIME} variable is used to match against the current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

%{TIME_YEAR} represents the current year ie 2019. This variables contains year value in YYYY format (4digits).

%{TIME_DAY} variable is used to match against the current Date ie (date of the day from 1 to 31)

%{TIME_MON} is used to match against the current month of the year ie 1 to 12.

%{TIME_HOUR} represents the current hour for example 1 if the time is between 1:00 and 1:59 .

%{TIME_WDAY} week day. This variable is used to match against the current day of the week in numeric format . For example 6 if the day is Saturday.

%{TIME_MIN} is used to match against current minute starting from 00. This variable returns number of minutes from 00 to 59.

%{TIME_SEC} used to match against current secind starting from 00. This variable returns number of seconds from 00 to 59.


To test these variables on your server, create a demo.php in your public_html folder and add the following php code :

<?php
echo $_GET["myvar"];
?>

Next add the following RewriteRule to your htaccess file :

RewriteEngine on
RewriteRule ^test /demo.php?myvar=%{TIME} [L]

Now visit yoursite.com/test you will see the content of demo.php file. Your demo.php file will show you the value of whatever variable was requested. You can manually change the variable in the RewriteRule’s destination ( /demo.php?myvar=%{TIME} ).

Time based URL rewriting examples

Suppose you have a website that is updated or maintenanced every friday and you want to redirect your website visitors to specific page ie under-construction.php on this day of week. The rewrite logic you will need for this will be read as :

If the day is Friday
Redirect all visitors to under-construction.php.

here is the RewriteRule:

RewriteEngine on
RewriteCond %{TIME_WDAY} ^5$
RewriteRule (.*) /under-construction.php [L,R]

The rule above redirects all of your website URLs to a single page under-construction.php if the condition is met ie (%{TIME_WDAY} is == 5) . 5 is number of weekday for friday.

This rule above redirects all of your site URLs including the target page url under-construction.php to itself which can cause a Redirect loop error on your server , to fix this error you will need to exclude the target URL from your RewriteRule regex so it can not match the target.

The following is the perfect version of the above rule :

RewriteEngine on
RewriteCond %{TIME_WDAY} ^5$
RewriteCond %{REQUEST_URI} !/under-construction.php [NC]
RewriteRule (.*) /under-construction.php [L,R]

More examples

To redirect your website URLs to a different location at 8PM , you can use the following Rule :

RewriteEngine on
RewriteCond %{TIME_HOUR} ^20$
RewriteCond %{REQUEST_URI} !/location.php [NC]
RewriteRule (.*) /location.php [L,R]

The rule above redirects your website visiters to /location.php if the server time hour is 20 which means 8PM . The rule will be applied from 20:00 to 20:59 .

Redirect all website traffic to example.com at 8:30PM

RewriteEngine on
RewriteCond %{TIME_HOUR}:%{TIME_MIN} ^20:30$
RewriteRule (.*) http://example.com/ [L,R]

The rule above will redirect your website visitors to example.com exactly at 8:30PM.

We used two variables in the RewriteCond test string %{TIME_HOUR} and %{TIME_MIN} separated by a colon : to test the server time using a regex based pattern ^20:30$ .

Hope you liked the post. Thank you for reading!

Categories
apache htaccess mod-rewrite

How to know whether mod-rewite is enabled on Apache server – AmitOverflow blog

How to check whether mod-rewite is enabled on Apache server

mod-rewite is a URL rewriting module provided by Apache. We use this module to rewite or beautify our site URLs.

Although all web hosting service providers have pre-installed this module but in some cases you must enable it yourself in order to use RewriteRules in htaccess.

In this post , I will show how you can know whether mod-rewite ( URL rewiting module ) is activated on your apache web server and how you to activate it yourself if its not already activated.

Keep on reading!!

How to know whether mod rewite is active ?

One of the simplest ways to check mod-rewrite is PHP’s function php_info() .

With php you can easily get informations about all installed/active modules on your server.
Checking mod-rewite by php

PHP’s php_info() function returns a list of all active modules on apache server. Create a file test.php in your web directory with the following code and save it.

<?php
php_info();
?>

Now open the file in your web browser. You will see a list of all available modules on your webserver. The test.php will show you contents something like the following:
mod-mime

mod-core
mod-rewrite
mod-ssl..etc

All module that your server is using will be printed. Read the file from top to bottom , if you don’t see mod-rewite that means the module isn’t installed.

Check mod-rewite by htaccess

You can also check whether mod-rewite is enabled on your server by htaccess.

Create an htaccess file in your web root directory and put the following code

RewiteEngine on
RewriteRule ^foo/?$ http://example.com [R]

Now visit : yoursite.com/foo . If mod-rewite is enabled Then the htaccess rule will redirect you to http://example.com else you will get an internal server error with 500 status code.

How to enable mod-rewite on Apache?

You can enable this module easily by editing your server.config file. Open your server configuration file and put the following line to enable the module :

AllowOverride all

This line tells server to read rewrite rules from htaccess file rather then reading server.config.

If your webhost doesn’t allow you to edit server.config file then contact your hosting service to enable it for you.

Hope this helps. Thanks for reading!

Categories
apache htaccess mod-rewrite

Deny access to multiple ip addresses using RewriteRule in htaccess

With a RewriteRule directive you can deny access to a specific IP address or multiple ip addresses at the same time. If you need to deny access to a visitor IP address you can use a RewriteRule directive in htaccess file that checks the visitor IP address and blocks access to that address.
Blocking IP addressess using RewriteRule is as simple as ABC. You don’t need to do anything except using a RewriteRule in an htaccess file. In this post I will show you three RewriteRule examples that deny access according to visitors IP addresses.

Deny access to a specific IP address

To deny access to a single IP address you can use the following Rule in htaccess:

RewriteEngine on
RewriteCond %{REMOTE_ADDR} ^1.2.3.4.5$
RewriteRule (.*) – [F]

This will deny access to this specific ip address. Visitors having this ip addresses will get a forbidden error. You can also replace F with R=403 its same as F .

Deny access to multiple ip addresses

It is possible to deny access to multiple ip addresses at once using a single RewriteRule directive. If you have more then one ip addresses to deny access to, you can use a regex based pattern to match against those ip addresses, the following is a basic regex pattern to exclude 3 ip addresses, you can manully add more ip addresses to the pattern :

RewriteEngine on
RewriteCond %{REMOTE_ADDR} ^(1.2.3.4.5|ip2|ip3)$
RewriteRule (.*) – [F]

The pattern (.*) applies to the entire site including all files and folders , if you want deny access to a specific file path , say /user.php repace the (.*) with ^user.php$ or if the user.php file is located in /foo folder then use ^foo/user.php$ .

Block access to a specific path

To deny ip based access to a specific path you can use :

RewriteEngine on
RewriteCond %{REMOTE_ADDR} ^1.2.3.4.5$
RewriteRule ^thispath$ – [F]

This will forbid access to /thispath for a specific ip address matching the pattern 1.2.3.4.5 .

Hope this helps. Thanks for reading!

Categories
apache htaccess mod-rewrite

Enforce https and www in a single htaccess rule – AmitOverflow blog

enforce https www in one redirection

It is quite possible to redirect http and non www requests to https and www with one single redirect using a RewriteRule in htaccess.
Assuming, you want your site visitors to always redirect to https://www version of your site regardless of they come by http or non-www you can use a single redirect Rule that can both non-https and non-www. The benifit using a single redirect is that your site URLs will load faster as the one single rule is triggered when your visitors visit the http or non www version of your site.

writing a single redirect rule

You need to use a combination of RewriteCond directives and an OR flag between them so that the rule can run if one of the conditions is true.
In the following example we will use two conditions to match against HOST and HTTPS header we use [OR] flag to make the rule run when either HTTP_HOST or HTTPS condition is matched.

RewriteCond %{HTTP_HOST} ^example.com$ [OR]
RewriteCond %{HTTPS} off

Explanations :
The first condition matches against the host header ie example.com. Replace it with your non-www domain name.
The second condition matches against HTTPS variable . The off represents http non-ssl. This condition is met when the URL scheme is http.
You can use RewriteRule directive just bellow the condition to redirect your non-ssl and non-www urls to https://www.

RewriteRule (.*) https://www.example.com/$1 [L,R]

The following is the complete htaccess rule to enforce ssl and www in a single redirect

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$ [OR]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://www.example.com/$1 [L,R]

http to https www generic rule

If you have more then one domain to redirect, then instead of using multiple above codes , you can just use one dynamic rule :

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www. [OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www.)(.+)$
RewriteRule (.*) https://www.%1/$1 [L,R]

Categories
apache Apache mod-rewrite and htaccess related Articles htaccess mod-rewrite

Set env variable in htaccess – Create Apache Environment variable using RewriteRule

Set env variables using htaccess
You can set an environment variable using your htaccess file. There are two ways to do this via an htaccess.

Setting env variable via RewriteRule

To set env variable through a RewriteRule, you need to use E flag. Syntex for the E flag is as follows
E=variable:value .

The following is basic mod rewrite example to set an environment variable. You can test the code on your live server to see how it works :

RewriteEngine on
RewriteRule (.*) – [E=foo:bar]

The rule above sets an env variable with foo as variable name and bar as variable value.

Set env variable via env directives

ENV can also be created by using directives that are especially designed for env purposes. The following directives are used for creating ENV :

  • SetEnvIf
  • SetEnvIfNoCase

SetEnvIf directive uses a regular expression based pattern to match against mod rewrite variable and you can set the variable based on mod rewrite server variable.
The following code sets an env named pageviews and value 2 when /foo/ uri is requested.

SetEnvIf Request_uri “^/foo/$ pageviews=2

SetEnvIfNoCase is same as SetEnvIf except for one thing. Nocase makes the pattern case insensitive meaning that the ^/foo/$ will also match /FOO/.