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 PHP

How to increase php upload_max_filesize with htaccess?

In PHP the default value of upload_max_filesize is 2MB and the default value for post_max_size is 8MB on the server but you can increase or decrease this size limit by modifying your php.ini or . htaccess file using post_max_size and upload_max_filesize .
You can manually adjust the post data size and file size using these directives in your php.ini. See a list of supported directives you can use in php.ini .
Also see How to increase upload_max_filesize in PHP an article on tecmint.com.

  • post_max_size directive represents the maximum data size your form can submit to server using the POST method.

    The following line in php.ini will set the maximum post size to 500mb which means that your form can submit data upto 500mb in one request.
    post_max_size = "500M"

  • upload_max_filesize represents the maximum filesize your form can submit to server. For example if this is set as the following in your php.ini :

    upload_max_filesize = "250M"

    Then you can upload a file that is upto 250MB in size to server . This won’t allow you to upload files that are greater then 250MB as it’s the maximum size limit set in the directive.

You can easily increase the file upload limit on php by modifying your ini file but not all hosting service providers allow you to do that. If you can not modify your php.ini then the another easy option is to edit it via the htaccess file.

Increase php maximum upload filesize by htaccess

Since htaccess is available on all types of hosting providers, you can easily edit your htaccess file to update the PHP filesize limit.
Add the following two lines to your htaccess . You can change the size according to your needs

php_value post_max_size 100M
php_value upload_max_filesize 100M

This will set the maximum size to 100MB for both . You can change the size as per your requirements.

I hope this article was helpful. Thanks for reading it!

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

Categories
Apache mod-rewrite and htaccess related Articles

How to create a custom 404 error page for website using htaccess

In this article I will show how you can create a custom Error page for your website . A custom error page is the one that is shown to your site visitors when they type a broken URL.
If you don’t want to show the dedicated error page then you can create your own page . With the step by step instructions , I will explain how you can easily set up your custom error page with the help of your htaccess file.

First create an error.php file in your web directory

First of all, you need to create a new file that will be served to visitors upon requesting a broken link.

Create a new file named 404-error.php . The file name is just an example here you can change it to whatever name you like.
Add your custom html to the web page . The example error text code is shown below :

Error 404

Sorry, the page you requested couldn't be found.

Save the file in your root web directory and go to the next step which is mentioned below.

Edit your htaccess file to add the custom error code

You will need to add a one single block of code to your htaccess to set up the custom error page redirection.
At the top of your htaccess file, put the following block of code :

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /404-error.php [L]

Make sure the rule is at the top or before other directives in your htaccess.
Don’t try to add this to your WordPress site. The solution won’t work with WordPress.

The code above checks the requested URL path if it doesn’t exist then the request is silently forwarded to the error page. This doesn’t change the URL but makes the internal redirection instead so when your visitors will request a broken link they will see the contents from the custom error file.

If you want to redirection to be visible to client , you can just and a [R] redirect flag to the rule.
Just modify the rule line like the following :

RewriteRule ^ /404-error.php [L,R]