Menu Close

11 useful htaccess snippets for mod_rewrite and htaccess beginners

4.1
(18)

Last Updated on July 22, 2021 by Amit

In this article today I am going to share 10 htaccess code snippets that will help you learn some basics of how URL rewriting and htaccess works on Apache server. With the htaccess code examples and explainations on this page you will be able to modify the code examples and create your own code for htaccess.
Table of contents (10 htaccess snippets)

  1. How to enforce WWW
  2. How to redirect URL with Query String
  3. How to enforce SSL for a specific directory
  4. Allow URLs without .php
  5. How to block ip addresses
  6. How to set a custom file as index
  7. Redirect a specific directory to another directory
  8. Serve subdomain from subfolder
  9. How to redirect all URLs to index.php
  10. How to deny access to a specific directory
  11. Htaccess ErrorDocument

If you want to learn some basics of Apache mod-rewrite , you can follow this tutorial hosted on this site.

htaccess code snippets for beginners

301 Redirect non-www domain to www subdomain

If you want to redirect your non-www naked domain to www subdomain , the rule is simple , quick and easy to follow. You just need to match against your non-www (naked domain) using a RewriteCond and then use a Rule that redirects all URLs to www subdomain.
The quick rule to enforce www is here :

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

Make sure to replace example.com with your domain name in the code above.


Redirect URL with Query string

To redirect URL query strings using RewriteRule we have to match against %{QUERY_STRING} variable in RewriteCond directive .
The RewriteRule bellow will apply to any incoming URL path of this form /foo/?q=bar .

If the path matches the Rule and the condition then it gets redireted to an external URL https://example.com/ with Redirect 301 status .
Here is the rule we are talking about :

RewriteEngine on
RewriteCond %{QUERY_STRING} ^q=bar$ [NC]
RewriteRule ^foo/$ https://example.com/? [R=301]

One thing to take note of in the rule above is a question mark “?” at the end of the target URL . It’s important as it discards the old query string from the new URL.
If you remove it the redirected URL will appear like https://example.com/?q=bar .
However if you want to pass the old query strings to the new URL, you can remove it.


Enforce SSL for a specific directory

If you want to enforce SSL for a specific directory , say Root / , then you can use the following simple rule in your . htaccess file .

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

The rule will only apply to your root directory and all its file but not subfolders. If you want the rule to enforce SSL for the entire site then you just need to remove the second RewriteCond .


Allow URLs without .php extensions

If you want to access your php files without using .php extension at the end of the URLs, then the rule is simple. You just need to rewrite your extension-less PHP files to their original versions .

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

This doesn’t remove php extension but makes it so that you can just visit /file instead of /file.php
.


Block specific IP addresses using RewriteRule

You can block a specific or multiple ip addresses using RewriteRule in an htaccess file.

To block a single ip address from accessing your website, you can use the following :

RewriteEngine on
RewriteCond %{REMOTE_ADDR} ^1\.0\.0\.$
RewriteRule .* - [R=403,L]

This returns a 403 forbidden error the specified ip address. To block multiple ips you can use RewriteCond directives with [OR] flag.

RewriteEngine on
RewriteCond %{REMOTE_ADDR} ^1\.0\.0\.$ [OR]
RewriteCond %{REMOTE_ADDR} ^2\.0\.0$
RewriteRule .* - [R=403,L]

You can remove multiple ips using RewriteConds with “OR” but just don’t use the OR flag with last condition.


Set a custom file as DirectoryIndex

If you need to use a different file instead of index.php or index.html as your directory handler, you can do this using a RewriteRule directive. You just need to rewrite your directory path to that file.
The code example bellow makes the demo.php your main index file for root. So you will see this file when requesting /

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

Here we are using an empty regex pattern ^$ to match the root directory because ^/$ can not be used on htaccess context.


Redirect a specific directory and all its URLs to another directory

If you want to redirect a specific directory and all its URLs to a new directory , you can either use a simple Redirect or RewriteRule in your htaccess file.

Example with Redirect :

Redirect 301 /dir1/ /dir2/

Short an simple. This one liner redirect not only reditects your /dir/ to /dir2/ but it also preserves the path. So a request for /dir1/foobar will get 301 redirected to /dir2/foobar .

Example with RewriteRule

If the above Reditect doesn’t work then you may try the following RewriteRule based solution

RewriteEngine on
RewriteRule ^dir1/(.*)$ /dir2/$1 [R=301,L]


Serve subdomain from subfolder

If your subdomain is currently pointing to your document root folder and you want to point it to a subfolder instead, you can use RewriteRule directive for this.
You just need to create a rule with a condition that checks the host header. If the host header matches sub.domain.com then the rule will rewrite it to a folder named “sub” . The following is an example of that :

RewriteEngine on
RewriteCond %{HTTP_HOST} ^sub\.domain\.com$ [NC]
RewriteRule .* /sub%{REQUEST_URI} [L]

Make sure to change the Domain name and folder name with your own in the code above.


Redirect all URLs to index.php

If you need to redirect all URLs to index.php then you can do this using the following rule in your htaccess file :

RewriteEngine on
RewriteRule !index\.php$ /index.php [L]

The code above silently forwards all URLs of your domain to index.php . If you want the redirection to be public and visible to browsers the you can replace the [L] with [R] for redirection


Deny access to a specific directory on Apache server using htaccess

If you want to protect a specific directory so that users can get a 403 forbidden error accessing it , you can use the following line in your htaccess

RedirectMatch 403 ^/folder/?$

This will return a forbidden error for example.com/folder/ .

You can also use RewriteRule to forbid a request for folder.

RewriteEngine on
RewriteRule ^folder/?$ - [F]

If your htaccess is in the folder that you are going to forbid , change RewriteRule’s pattern from ^folder/?$ to ^$ .

Using ErrorDocument in htaccess

ErrorDocument directive is used to handle different types of server errors. With ErrorDocument you can redirect specific error requests to your custom page. An example of 404 error is the following :

ErrorDocument 404 /404.php

With this code you can redirect your not-found site URLs to your custom page /404.php .


I hope these htaccess code snippets were helpful . Thanks so much for reading this post.

How useful was this post?

Click on a star to rate it!

Average rating 4.1 / 5. Vote count: 18

No votes so far! Be the first to rate this post.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

code