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
htaccess WordPress

How to modify your htaccess on WordPress | Add custom rules WordPress htaccess

How to modify WordPress htaccess file

In this article I will give you a quick overview of what the wordpress htaccess is , how it works and how you can manually add your custom code to your htaccess on WordPress site.
With WordPress blog CMS you get a default htaccess file that the WordPress uses to manipulate your blog URLs.

Your htaccess file on WordPress is responsible for pretty URLs of your site or blog.

Your WordPress/. htaccess looks something like :

RewriteEngine On
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /index.php [L]

You can see that the WordPress uses a simple set of Rules to redirect your blog URLs to the main index.php file.

WordPress forwards all requested URLs (not pointing to an existent file or directory) to the main index file . And the index file contains a script that checks the $_SERVER[‘REQUEST_URI’] variable to find data in databases.

Here is an example to demonstrate the wordpress URL rewriting logic :
To open a wordpress post, You type the post URL

https://example.com/22/10/hello-world

into your browser address bar.
The fist thing that happens on the server is , the WordPress htaccess is read.
Your WordPress htaccess then forwards the URL path to /index.php for processing.

The index.php file on WordPress root directory then reads the REQUEST_URI string from URL and returns the data from database.
It’s pretty simple. The URL Rewriting logic used by WordPress is awesome and easily understandable as it uses the mod-rewrite (a URL Rewriting module) provided by Apache server.

The htaccess file in your wordpress root directory doesn’t affect other directories and files on your server. The htaccess only forwards those paths that do not exist as an actual file or directory on your server.

The following two conditions used by WordPress htaccess prevent your real files and folders from being forwarded to the index.php

  1. RewriteCond %{REQUEST_FILENAME} !-f
  2. RewriteCond %{REQUEST_FILENAME} !-d

The condition is there to protect your original files.
The second one protects your directories.

Quite simple.. isn’t it?

How to modify WordPress htaccess

Ah, this is a frequently asked question on the internet but here I will give you an unique solution and explain how you can add your custom code to htaccess.
Most often you will you need to edit your wordpress htaccess to add your custom Redirect or RewriteRule .
Some wordpress users who don’t know how to edit htaccess sometimes alter the wordpress default code and that results either in 500 server error or the htaccess code not being read by server at all.

Where to add the custom code?
This is really important to know where you should put your custom code in htaccess. Bellow WP rules or At the top because it really matters.
If you put your custom “RewriteRule” bellow the “WordPress rules” then your rule will never be found by the server as WP rule overrides it.

So you must keep your own RewriteRule at the top or before WordPress code .

Another important thing to note here is that if you are going to add a custom redirect using Redirect or RedirectMatch directive then you will need to replace those Redirects with RewriteRule otherwise your redirection won’t work.
RedirectMatch and Redirect are directives of Apache alias module while the RewriteRule is part of Mod-rewrite a different module . WordPress uses mod-rewrite so your custom redirects should also be using the same module. Simply change your Redirect or RedirectMatch to RewriteRule otherwise it will be overridden by the default WordPress rules.


If you are new to htaccess and want to learn some basics of URL Rewriting, you can follow my Htaccess tutorial for beginners .

Categories
apache Apache mod-rewrite and htaccess related Articles htaccess

Apache .htaccess tutorial for beginners | Learn URL rewriting and basics of mod_rewrite – helponnet.com

htaccess tutorial

htaccess has always been a confusing topic for all Apache users especially for newbies who are learning to write RewriteRules to modify URLs via an htaccess file. The reason why some people find it confusing is because the Apache mod-rewrite documentation is hard to follow and there are no easy to follow htaccess step by step tutorial available on the internet.
I often see users struggling with their RewriteRule code on StackOverflow and I help them fix issues when I can.

In this 10 minute read article I am going to post an htaccess short step by step tutorial for people who wish to learn some basics of URL rewriting on Apache server.
If you follow this tutorial from top to the bottom then I am sure you will learn alot about URL rewriting and you will have some basic idea to create your own RewriteRules.


What is an .htaccess file?

What is an htaccess file

It’s a directory level configuration file used by Apache web server to modify URLs , directory appearance and other server settings.

.htaccess is a dot prefix file.
The name starts with a single dot . and ends with htaccess .

You can change the name to make it look something like htaccess.txt from your server.config file.
The benefit of using an htaccess file is that it’s easy to edit and available on all types of hosting services.

The downside of using an .htaccess file is that it slows down your server performance as it’s read on each request but that’s not going to be a big issue for you.
You can see the world’s largest CMS WordPress also uses an htaccess file to shorten the blog URLs.
An htaccess file is easy to maintain and set-up that’s why many web developers prefer to use it rather then editing the main configuration file.

Apache mod-rewrite

Rewrite module aka mod-rewrite is a powerful Apache module that provides URLs rewriting functionalitis to Apache users.
The official documentation of mod_rewrite is available on Apache mod_rewrite.
Mod-rewrite provides URL rewriting directives such as

RewriteEngine
RewriteBase
RewriteRule
RewriteCond
All these directives are used in an htaccess file to manipulate incoming URL requests and other settings on the server.

You will learn more about these directives later in this article but for now just focus on what the Rewrite module is and how to enable it.
Almost all live web hosting providers will provide you Apache server with pre-installed mod-rewrite. But in some rearest cases if it’s not already installed then you can ask your service provider to enable it for you or you can also enable it yourself by modifying the server configuration file that’s located in /etc/httpd/conf/httpd.conf .
Open this file for editing and replace the line AllowOverride none to AllowOverride all this will then make it possible to use mod-rewrite in an htaccess file.

To verify whether your server supports mod-rewrite in htaccess , you can do the following :

  • Create an .htaccess in your public_html folder.
  • Put some random texts to your htaccess file like “fooooobarrr” .
  • Now, visit any URL on your site.

If it generates a 500 internal server error then the mod-rewrite is enabled on your server otherwise if you don’t get any error then you will need to enable this using the easy method I mentioned above.

Let’s create our first Hello-world RewriteRule

If you are learning to write htaccess rules while following this article , then I suggest you start learning with an empty htaccess file as with an empty Htaccess you can delete the code if something goes wrong or you want to test a different code, this will improve your learning experience.

Create an htaccess file on your document root and put the following contents in that file :

RewriteEngine on
RewriteRule ^helloWorld$ /index.php

Save the htaccess file and type the following URL into your browser address bar :
https://yourdomain.com/helloWorld
You will see the real rewrite mazic happening now.
The rule will internally map your URL path /helloWorld to the destination file /index.php.
The redirection happens behind the screen. You will see contents of the index.php file on the /helloWorld path.

Congratulations , you have written your first helloWorld rule successfully.
Now let’s understand how the code above works. Let’s understand it line by line.

  • RewriteEngine on : This directive turns on the engine for rewriting URLs.
    This directive should be placed once at the top of your htaccess.
    There is no need to add “RewriteEngine” with each rule, just one single line at the top is enough.
  • RewriteRule ^helloWorld$ /index.php : This is a RewriteRule directive provided by mod-rewrite. This line rewrites the request from /helloWorld to /index.php .
    You might have noticed one thing that our Rule’s pattern doesn’t start with a leading slash / .
    This is because RewriteRule uses a relative path in its pattern so ^/helloWorld$ will not work in htaccess but in a server.config file.

Okay, now I hope you have had some basic idea about how to create a simpe RewriteRule.
Now we will learn about other parts of a RewriteRule.

Mod-rewrite Flags

Flags are optional in RewriteRule but you will need to use them in most cases.
Flags provide additional instructions to a RewriteRule.
For example a RewriteRule with [R] flag tells the rule to make an external redirection of URLs.

See a list of most commonly used flags in mod-rewrite .

Flags are used inside sequere brackets [] .
You can use multiple flags with a RewriteRule seperating them by a comma char ,.

Flags are optional in RewriteRule but you will most often need to use them in Rule to change the URL rewriting behaviour.

You will needv to use [NC] flag in the following Rule:

RewriteRule ^foobar$ /index.php

NC stands for NoCase, this flag is used to match both uppercase and lowercase chars in URI.
With NC, the rule above will match the following both URIs :


/foobar

and
/fOObAr
otherwise without this flag, by default RewriteRule only matches the case sensitive URI string.

You can learn more about flags on this post .

Conditions in RewriteRule

You can use conditions with your RewriteRule to rewrite or redirect your site URLs based on some specific conditions.

RewriteCond directive is used for this purpose.
With RewriteCond you can rewrite your URL based on host , https , request URI headers.

Check this post to learn more about using RewriteCond directive.
You can use if/else logic for RewriteRule .

The following Rule uses RewriteCond to redirect the URL based on host header. The condition used in this rule can also be read as
“If host ==example.com then Redirect .

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule ^foobar$ /index.php [R]

This rule will redirect /foobar to /index.php if the condition is met.

You can use multiple conditions with a single RewriteRule .

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteRule ^foobar$ /index.php [R]

The conditions above uses [OR] flag. This makes one of the conditions optional. So you can read it as :
“If host ==example.com OR host==www.example.com” then Redirect.

To redirect http URLs to https , you need a condition logic. That checks if the incoming URL is using http scheme , then redirect the URL to use https :

RewriteEngine on

RewriteCond %{REQUEST_SCHEME} ^http$
RewriteRule (.*) https://example.com/$1 [R]

I hope now you have had some basic idea of how conditions work and how to use them with RewriteRule.

Regex in mod-rewrite

Mod-rewrite directives RewriteRule and RewriteCond use a regular expression based pattern that makes the match easier.
With a Regex based pattern a single RewriteRule can match multiple URIs.

If you want to learn Regex , you can follow this tutorial .

The following rule with regex pattern can either match /helloWorld or /hello ladies :

RewriteEngine on
RewriteRule ^(helloWorld|hello ladies)$ /index.php

The match is saved in $n variable . Since we have one capture group in the rule above , the match is saved in $1 .

You can use the matched value in the destination string of RewriteRule.

RewriteEngine on
RewriteRule ^(helloWorld|hello ladies)$ /index.php?q=$1

The rule above rewrites /helloWorld to /index.php?q=helloWorld

You can use Regular expressions with RewriteCond :

RewriteCond %{HTTP_HOST} ^(www\.)example.com$

The condition above checks both www and non-www domain .

Isn’t it easier with Regex?

Comments in htaccess code

In any programming languages , comments are used to explain the block of code. Like in PHP we use # to write a single line comment and /*…*/ for multiple lines.
In htaccess , you can only comment out a single line using the hash character # .

Anything that goes after # is treated as a comment in htaccess.

#This is a comment.
#This is another comment.

To explain an htaccess code you can start your comment with a # character but keep in mind that the # is a single line comment. To add multiple line comments you will need to start each line with a hash character like the example shown below

#redirect http to https
#This rule also reditects non-www to www at the same time
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www
RewriteRule (.*) https://www.example.com/$1 [L,R]

Error handling with htaccess

With an htaccess file you can handle server errors with just a few lines of code.
On Apache there are different types of server errors . Some most common errors are :

  • 403 (Forbidden error)
  • 404 (Not found error)
  • 410 (Gone)
  • 500 (Internal server error)
  • 503 (Server unavailable) .

With an htaccess file you can easily handle these server errors using ErrorDocument directive which is part of Apache core module.
403 is the error status code which represents a “Forbidden error” (Access to the resource is denied) .
To redirect your site URLs to a different location when this error occurs, you can use the following code in htaccess :

ErrorDocument 403 /403.php

Here 403.php is the file that is called when you request something that is protected on your server.

The code below handles 404 “not found” URLs.

ErrorDocument 404 /404.php

The same code format is used to handle other server errors except 500 (Internal server error) . You need to handle it from your main server configuration file.

RewriteRule code examples

WWW to non-www

With the following rule you can redirect your www subdomain to root domain :

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule (.*) https://example.com/$1 [R=301,L]

Redirect non-www to www (naked domain to www subdomain)

If you want to redirect your root domain to www subdomain , here is the rule you can use to enforce www on your website :

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule (.*) https://www.example.com/$1 [R=301,L]

Change directory index file

By default , your server shows index.html , index.php or whatever index file exists to client when a directory is direct accessed , but you can change this behaviour by simply using the following line in htaccess , read more about DirectoryIndex

DirectoryIndex somefile.php

Access all files without adding an extension at the end

If you need visit your file URLs without adding extension at the end , for example : to visit /file.php as /file you can use the short code below in your htaccess :

Options +Multiviews

Enforce SSL

You can redirect your insecure traffic (http) to the secure version (https) using this rule :

RewriteEngine on
RewriteCond %{HTTPS} off [NC]
RewriteRule (.*) https://example.com/$1 [R=301,L]

Add a trailing slash

To add a trailing slash to your URLs , you can use the following :

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !/$ %{REQUEST_URI}/ [R,L]

Allow non-php extension

If you want to access your .PHP files without using extension at the end , you can use :

RewriteEngine on
RewriteCond %{REQUEST_FILENAME}.php -f
RwriteRule ^(.+?)/?$ /$1.php [L]

More rules : 5 Awasome htaccess rules you can just copy & paste .

.htaccess tutorial pdf

This htaccess tutorial is available for download as PDF format. You can Download this htaccess tutorial as .pdf and use it for personal and educational purposes only.

I hope this tutorial was helpful. If there is anything that you couldn’t understand or you need my help with htaccess , you can post a comment bellow.

Thank you so much reading this.

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

Converting a long query string URL to short and SEO friendly using RewriteRule in htaccess

SEO friendly URL with htaccess RewriteRule

In this post you will learn how to shorten a long URL with very simple steps using RewriteRule directive in an htaccess file.

We are going to change a really long URL that is hard to type , hard to remember and not good for SEO in this article.

We have a URL of the following format :

https://example.com/user.php? username=foobar&action=profile

You can see the URL is really hard to memorize as it contains query strings .

If you have a user registration website where users create their profile then the original structure of their profile URLs might look like the one I mentioned above.
It’s long but the length of URL doesn’t matter what matters the most is the structure of URLs.

Search engines like Google and Yahoo can not index those links properly as these links are externally pointing to the same php file.
You might sometimes get a “duplicate contents err” from search engines from those type of URLs.
To fix this what we can do is rewrite those URL to make them SEF URLs.

With RewriteRule , you can convert the URL above into a clean and short one. You can change that URL to
https://example.com/user/foobar/profile or even more shorter https://example.com/foobar/profile .

These are the unique and memorable URLs .

How to convert a long URL in short one using RewriteRule

You can use your htaccess file for this.
The following are the steps to create friendly URLs using htaccess file :

  • Create an .htaccess file in your document root folder if it doesn’t already exist.
  • Verify your htaccess and mod-rewrite. You need to make sure your server is reading the htaccess file and the rewring module is enabled.
    To verify it’s working , put some random texts in the htaccess file , and visit your site. If you receive a 500 internal server error then everything is ok and you can proceed to the next step. If the htaccess or mod-rewrite isn’t enabled then you won’t see any error vising your site with random texts in htaccess.
    You can enable mod-rewrite on your server just by changing a single line in your server.cofig file. Open that file and find the line AllowOverride none . Change this line to AllowOverride all . This enables the URL rewriting module to be used in an htaccess file.
    In case you are on a shared hosting and you don’t have access to the configuration file , you can ask your hosting provider to enable it for you.
  • Now create your rule to shorten the URL.
    Assuming our original URL is :
    https://example.com/users.php? username=foobar& action=profile
    and we want our new URL as :
    https://example.com/user/foobar/profile .
    We will need to map the URL to the old one. By URL mapping here I mean “the new URL will redirect to the old one while preserving the new URL path” .
    We can write a rule in our htaccess file to achieve this.

    RewriteEngine on
    RewriteRule ^user/foobar/profile$ /users.php?username=foobar& action=profile [L]
    

    The rule does what I mentioned above. But the problem with this is that it only applies to a single user URL.
    To make the rule dynamic for all users , we can use a regex based pattern in our rule to so that it can match any user path.

    RewriteEngine on
    RewriteRule ^user/(.+)/(.+)/?$ /users.php?username=foobar& action=profile [L]
    

    Now it’s perfect.

    The rule applies to multiple users at the same time.
    The rule works when you type the new URL example.com/user/foobar/profile into your browser address bar.
    A request for example.com/user/foobar/profile is then internally forwarded to the original file /users.php .
    The first path segment /user is just an indetifier .
    The second path segment /foobar is the name of user. The RewriteRule automatically pick it up from the URL using (.+) pattern and saves the value in $1 var so that it can be used in the destination file . We use the $1 username value to fatch usernames from “username=foobar” query perameter.
    The third segment “/profile” is matched by the second capture group (.+) in our pattern . The captured value is saved in $2 so that we can use it to retrieve the “action=profile” query perameter.

The rule is as simple as ABC . I hope you learned something interesting from this post.

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

Images JS and stylesheet files failed to load after using RewriteRule in htaccess?

Fix images , css , js on RewriteRule
One of the most common issue every mod-rewrite users encounter while using RewriteRule directive to shorten their URLs is the IMG, CSS , JS and other relative resources failing to load.
If you are using RewriteRules to rewrite your URLs then you may sometimes face this kind of issue . This is a normal behavior. There is nothing wrong with your htaccess configuration and there is nothing that can be done to fix this by editing or by adding something to your htaccess file.
The solution to fix this issue is really simple and it doesn’t require a huge lines of code. Just a one single html tag can fix your problem.
In this post , I will give tell you how to fix your CSS, JS, and other relative resources for rewritten URL, but before we jump to the solution let’s first understand the reason why our files failed to load on a rewritten path.

Why IMG, CSS, JS failed to load on a rewritten path

Webpage without css htaccess

Your files failed to load because you are linking them on a web page using a relative path like in the following image example :
<img src=”something.jpg”>
Your image file should work if you use an absolute path starting with the dir name as “/” for root :
<img src=”/something.jpg”>
Now see the following rule :

RewriteRule ^foo/$ /demo.php [L]

The rule above will internally map a request for /foo to /demo.php
If you visit the file path /demo.php you will not face any issues with your relative resources but if you visit the new rewritten path /demo/ then your relative resources will fail to load. This is because the web server thinks /demo/ is a base directory and tries to append it to all relative resources changing your image path from
<img src=”something.jpg”>
To
<img src=”demo/something.jpg”>
As you can see the “demo” path has been appended to the image . Since /demo/something.jpg doesn’t exist thus the image 404s and fails to load.

How to solve IMG CSS JS not loading on rewritten path

It’s very simple to fix this problem. You either need to use a base tag or change the relative path to absolute in your files.
For example , if you are linking a js file using a relative path in your document, change its path from :
<script src=”something.js”>
To <script src=”/something.js”>
and do the same for images or other relative resources. While this can be tough to manually change files path one by one if you have hundreds or relative links in a document, in that case what you can do to quick fix it is just add a single liner base tag to the head section of your document.
<base href=”/”> inbetween <head> and </head> will fix all relative links in your document.

Categories
apache Apache mod-rewrite and htaccess related Articles htaccess

How to set an ENV (Environment) variable using RewriteRule in htaccess

Setting environment variables by htaccess

There are different ways and directives to set an environment variable on Apache server through a htaccess file. One of the most common and the easiest way to set an Environment variable is by using a RewriteRule directive. It’s the easiest method because you can rewrite your domain requests based on env and also you don’t need to write multiple lines of code a one single line of Rule can do this for you.
In this article I will show you how can set the ENV variable using our htaccess file. I will post some code examples to explain the process.

Setting an ENV via mod-rewrite

You can use the mod-rewrite E flag which is short for ENV to set the variable on your server.
The following RewriteRule example sets an ENV variable named foo value bar :

RewriteEngine on

RewriteRule .* - [E:foo=bar]

The rule above will set the ENV foo and assign bar as value to it. The pattern .* matches all URLs meaning that if you visit any URL of your site the ENV will be set. You can change or restrict the pattern to match a specific path only if you want to.
For example the pattern ^demo.php$ will set the ENV only if the /demo.php is requested.

How to check the ENV variable

To check if the variable is set or notset you can match against %{ENV:varName} in a RewriteCond.
The following example checks if the variable “foo” is set and contains bar as value.

    RewriteCond %{ENV:foo} ^bar$

To set the variable if its not already set you can use a RewriteRule

RewriteEngine on

RewriteCond %{ENV:foo} ^$
RewriteRule .* - [E:foo=bar]

The ^$ in condition pattern above checkeks an empty string. If the foo variable is empty/notSer then the rule is triggered and sets the ENV variable.

Setting ENV using mod-env

Apache ENV module provides three different directives to set an environment variable in htaccess and server configuration file.

  • SetEnv directive
  • SetEnvIf directive
  • SetEnvNoCase directive
  • These three directives can be used to set the ENV variable if you don’t want to use a RewriteRule based solution.
    SeEnv directive takes two perameters env_name and env_val .
    The following example sets an environment variable named “foo” and value “bar” :

    SetEnv foo bar
    

    You can use SetEnvIf directive to set the variable conditionally based on requested URIs and Host headers, for example, If you need to set ENV variable only when the request is for /file.php , you can use the following :

    SetEnvIf request_uri ^/file.php$ foo=bar
    

    SetEnvNoCase is same as the SetEnvIf except that it ignores the case of characters in pattern, this also matches a request URI string with uppercase characters ie : /FiLe.php .

    SetEnvIfNocase request_uri ^/file.php$ foo=bar
    
Categories
Apache mod-rewrite and htaccess related Articles htaccess url-rewrewriting

Redirect a domain to another domain without changing URL with htaccess

Redirect domain without changing URL
In this post I will show you how to write a rule to redirect your domain to an external domain without changing the URL in browser address bar .

Redirect domain without changing the URL .
You need to enable proxy module on your apache web server in order to map/redirect (internally) your domain to an another domain that is being hosted on a diffrent web server.
once the proxy module is enabled , you can then use mod-rewrite [P] flag which is mainly used to proxy requests between two diffrent HTTP_HOST headers .

Using P flag to rediect domain URLs

P flag is used to rewrite domain URLs between two diffrent host headers .
Assume you have a domain named www.example.com and you want to redirect all its URLs to a diffrent domain named example2.com without changing the browser URLs or preserving the domain name, you can use the following RULE in your htaccess file for this kind of internal redirection.

RewriteEngine On

RewriteRule (.*) https://example.com/$1 [P]

or the following domain specific rule :

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule (.*) https://example2.com/$1 [P]

Your webserver might return a 500 internal server error for using these rules with P flag if you have not enabled the proxy module. If you have already enabled the module then any request for www.example.com domain will be served from the example2.com domain.

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

Map a subdomain to subfolder with htaccess

Reditect subdomain to subfolder using htaccess
With an htaccess rewrite ,it is quite possible to map your subdomain to subfolder if its not already pointing there.
Suppose, you just created a new subdomain named bar.example.com and its currently pointing to you root directory , you can simply use a RewriteRule to map it to a new folder.
This article will teach you all about how it can be done with just a few lines of htaccess code.
Okay, so you have created a new subdomain , and now want to map it to a different folder, the following rule can help you with that. Just copy and paste it to your htaccess file and don’t forget to change the domain name.


RewriteEngine on

RewriteCond %{HTTP_HOST} ^bar.example.com$ [NC]
RewriteRule ^(.*)$ /folderName/$1 [L]

The rule above will point your subdomain and all its URLs to /subfolder/
For example, a request for bar.example.com/file.php will be served from /subfolder/file.php . This doesn’t change the browser URL.

Categories
apache htaccess url-redirection

http to https and enforce www in one 301 redirect on htaccess

Htaccess redirect http to https non www to www
If you are looking for an htaccess RewriteRule that enforces www and https in one redirection and without creating multiple redirects then you have come to the right place. On this article I am going post a 100 percent working rule that you can just copy and paste to your htaccess file.

Here is the RewriteRule :


RewriteEngine on

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

How to use the code : You can just copy and paste it to your htaccess. Since this redirects all non-www and non-https URLs to https://www this is the main rule and should be placed at the top of your htaccess file.
What needs to be changed : You need to change the domain name to your domain. Replace example.com with yourdomain.com in the code and test the rule , if it works then change R to R=301 in the flag section to make the redirection permanent and browser cache-able.

http to https multiple domains

If you are looking for a rule the redirection dynamically, and you don’t want to change hostname manually, then the following one should fullfill your need as it can redirect multiple domains


RewriteEngine on

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

The rule above applies to multiple domains at the same time. You don’t need need to change anything in the rule as it automatically detects host and https headers.

RewriteRule for Cloudflare users

If your domain is on cloudflare then the rules I posted above might fail to work as Cloudflare doesn’t recognise %{HTTPS} variable. Cloudflare has its own variable to test URL scheme. RewriteEngine on RewriteCond %{HTTP:CF-Visitor} ‘”scheme”:”http”‘ is the variable Cloudflare uses to detect URL scheme.
So in that case, you can you can use the following RewriteRule :


RewriteEngine on
RewriteCond %{HTTP_HOST} !^www. [NC,OR]
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
RewriteCond %{HTTP_HOST} ^(?:www.)?(.+)$
RewriteRule ^(.*)$ https://www.%1/$1 [L,R]

Categories
apache Apache mod-rewrite and htaccess related Articles htaccess

Mod-rewrite NE flag uses and code examples

NE flag htaccess
In this article we will learn about mod-rewrite NEflag. What this flag is used for and why we should use it all these frequently asked questions are answered in this article.
NE stands for NoEscape
We use this flag in RewriteRule to tell the engine not to escape special characters like # , & .. in URLs.

Here is an example of how mod-rewrite works without NE flag :

RewriteEngine on
RewriteRule ^foobar$ https://example.com/#foobar [R,L]

The rule above will redirect /foobar to https://example.com/%23foobar
As you can see the redirected URL path has changed to %23foobar . The # changed to its hexadecimal value%23 .This is because the rewrite engine converts special characters in redirected URL to their hex code. The characters are escaped by default if NE flag is not present in RewriteRule.
RewriteRule example with NE :

RewriteEngine on
RewriteRule ^foobar$ https://example.com/#foobar [NE,L,R]

The rule above does the redirection of the URL perfectly fine. This doesn’t change # to %23 as we used NE flag that tells server not to do so.