10+ Mod_Rewrite Rules You Should Know
Mod_rewrite is an Apache-based rewrite engine for dynamically rewriting URLs. It's built into Apache servers natively, though not enabled by default.
It's capable of functions beyond simple rewrites, though, some of which are included below.
Internet's universe... photo by CLUC shared under Attribution-NonCommercial-NoDerivs 2.0 Generic (CC BY-NC-ND 2.0) licence
Internet's universe... photo by CLUC shared under Attribution-NonCommercial-NoDerivs 2.0 Generic (CC BY-NC-ND 2.0) licence
Turn Mod_Rewrite On
Mod_rewrite is used through your .htaccess file. Place the following code at the beginning of your .htaccess file to turn mod_rewrite on:RewriteEngine on(Don't forget that .htaccess commands are case-sensitive.) This code needs to be entered at the beginning of any .htaccess file using mod_rewrite.
The Basic Mod_Rewrite Layout
The basic format for a mod_rewrite command is:RewriteRule Pattern Substitution [Flag(s)]
URLs are Always Relative
The URL you redirect to is always relative to the directory in which your .htaccess file is placed. So if it's in the root directory, URLs are all in relation to the root directory; if it's in a sudirectory, URLs are in relation to that particular subdirectory.A Basic Redirect
If you just want to create a simple 301 redirect from one URL to another, then use the following code:RewriteRule ^fileone.html$ filetwo.htmlThis is a very basic rule that means any requests for fileone.html will be sent to filetwo.html.
Require no "www"
This bit of code will make it so visitors to your site don't need to type in the "www" bit of your website address.RewriteCond %{HTTP_HOST} !^domain.com$ [NC] RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]
Block a Specific IP Address
If you want to block someone coming from a specific IP address from accessing your website, you can use the following code:RewriteCond %{REMOTE_ADDR} ^(A.B.C.D)$ RewriteRule ^/* http://www.domain.com/sorry.html [L]Replace the A.B.C.D with the IP address you want to block (don't forget to leave the "" before each dot, which escapes the character).
Block Specific User Agents
If you want to block a group of IP addresses using the same User Agent (bot), the following code with do it:RewriteCond %{HTTP_USER_AGENT} UserAgent RewriteRule .* - [F,L]Just replace the "UserAgent" bit with whatever user agent you want to block. You can also block more than one at a time by replacing the top line in that code with something like this:
RewriteCond %{HTTP_USER_AGENT} UserAgentA [OR] RewriteCond %{HTTP_USER_AGENT} UserAgentBYou can put as many user agents in as you want, just make sure you end each line with [OR] (with the exception of the last line, of course).
Strip Query Strings
Let's say all the pages on your site other than your home page are formatted as follows, with query strings instead of page names: http://www.domain.com/home.html?example=12345abcd Those aren't very pretty, and on top of that, search engines will show a bunch of duplicated "home" pages. If you want to get rid of the query string in your page URLs, use the following code:RewriteCond %{QUERY_STRING} example= RewriteRule (.*) http://www.domain.com/$1? [R=301]This not only gets rid of the query string, but also the preceding question mark.
Set up a Default Image
Using a default, backup image in case of broken images can make your site look more professional. Use the following code to redirect to a default image for any image whose file cannot be found.RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^images/.*.jpg$ /images/default.jpg [L]Of course, you can change the ".jpg" bit to whatever file type you're using. Make sure you have an image called "default.jpg" or change that to whatever your default image filename is.
Prevent Hotlinking
The last thing most website owners want is other sites stealing their content or worse—hotlinking to their images and stealing their bandwidth. Here's a simple bit of code that prevents it:RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^http://(www.)?domain.com/ .*$ [NC] RewriteRule .(gif|jpg|swf|flv|png)$ /feed/ [R=302,L]Make sure you change the "domain.com" bit to your own domain name.
Redirect to a Maintenance Page
If you need to take your entire site offline for a bit and redirect to a maintenance page (or some other page), use the following code:RedirectMatch 302 ^/ /maintenancepage.htmlChange the "maintenancepage.html" bit to wherever your maintenance page file is located.
Redirect Multiple Domains to a Single Domain
If you have multiple domains pointing to your site, it's possible you could take a hit in the search engines for having duplicate content. Use the following code to redirect visitors from two domains to just one:RewriteCond %{HTTP_HOST} ^www.domain.net$ [NC,OR] RewriteCond %{HTTP_HOST} ^domain.net$ [NC,OR] RewriteCond %{HTTP_HOST} ^www.domain.net$ [NC] RewriteRule ^(.*)$ http://domain.net/$1 [R=301,L]
Remember the Filesystem Always Takes Precedence
The filesystem on your server will always take precedence over the rewritten URL. For example, if you have a directory named "services" and within that directory is a file called "design.html", you can't have the URL redirect to "http://domain.com/services". What happens is that Apache goes into the "services" directory and doesn't see the rewrite instructions. To fix this, simply rename your directory (adding an underscore to the beginning or end is a simple way to do that).Remember:
- Because mod_rewrite works within the .htaccess file, commands are case sensitive.
- Always back up your .htaccess file before making any changes to it. This way, if there's a problem, you can easily restore your site.
More Resources:
- Modrewrite.com - This is a great site that offers a forum, a beginner's guide, and links to more information about mod_rewrite.
- Mod_Rewrite Tips and Tricks - A great article on the basics of mod_rewrite and some beginner and advanced techniques.
- Mod Rewrite Tips and Tricks - This site offers a few basic tips for mod_rewrite.
- Apache Mod_Rewrite Cheat Sheet - This cheat sheet offers information on the most-used items for building a mod_rewrite pattern.
- Learn Apache mod_rewrite: 13 Real-World Examples - This is a much more advanced article from SitePoint.
- Module mod_rewrite URL Rewriting Engine - The official documentation from Apache.
- .htaccess Rewrite Tips for Using RewriteRule and RewriteCond for .htaccess mod_rewrite - A great guide to a number of different mod_rewrite patterns.
- Tip for Configuring Apache's Mod_Rewrite - Five great tips for mod_rewrite configuration.
- Several Mod_Rewrite Tricks for a Better Web Application - Covers a number of basic and more advanced mod_rewrite tricks.
I am trying to redirect
kategorier?uid=[number]
to
index.php?option=com_comprofiler&task=userProfile&user=[number]
but it does not work, what am i doing wrong?
RewriteRule kategorier\?uid=([0-9]+) index.php?option=com_comprofiler&task=userProfile&user=$1 [R=301,L]
Regards Robert
Unfortunately this did not help me with my issues. Thanks though
thanks for your post , that’s really help
but how to avoid css,js and images dirs reWriten ?
thanks for help
Great resource! After weeks/months of trying to get some basic mod rewrite sources, this site gave me all the answers I needed. Thanks!
First and foremost, thanks for this. Helpful.
fyi More Resources: couple out of date links in there
i want to redirect 20 php urls to single url. iam using below command, Can any one confirm is it work or not?
RewriteRule ^/(korean/|portugues/|francais/|japanese/|deutsch/|italiano/|espanol/|chinese/|russian/)?main/piv\?.php /page.php?page_id=$1 [L,R=301]
Is there a way to deny an entire tdl? For example if I want to deny anything coming from .ru (russia) domains , can this be don using deny rules or is this only possible with the actual IPs.
Hi Cameron Chapman,
My website is running under https and all pages are using https. But one iphone api url is need to use http.
I need to change https://xxxxxxxxx.com/system/miscellaneous/api url to use http rather than https.
Also if anyone will use http://xxxxxxxxx.com/system/miscellaneous/api url, it should not redirect to https.
My current .htaccess in DocumentRoot as follows.
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* ./index.php
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{SERVER_PORT} ^80$
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
Please help me. It is urgent.
Regards,
Kunu
Regarding hotlink-blocking, I wrote a PHP script to circumvent just this after writing a very nice review of a webpage on my stumbleupon page with IMG tag pointing to cool image on the page that I felt was likely to attract visitors to check that page considerably better than just my writing and ending up with my article blaming me, in very insulting and rude words, for being bandwidth stealing low-life scum using hotlinking for my benefit on his expense.
It made me feel bad, for I was merely using his bandwidth to attract visitors to his site, and while causing perhaps some extra traffic from those who saw my review but didn’t visit his page it provided more visitors to his site for compensation – I don’t think it’s a bad deal and he certainly didn’t have to insult me that badly…
I made a PHP script that, using my bandwidth to promote his and other hotlink blockers sites… Unfortunately also any such site I would use it would get two requests for same image when someone visits the page through mine as normally the visitor would get it from browser cache when loading the page – but really the only one who might notice any impact because of increased bandwidth use could be the visitor, and even then only if using really bad connection, like GSM/GPRS :)
Good thing is, I now have PHP script to not only counter hotlink block for images but also, since I didn’t feel that writing script just for that was worth of my time, I made it’s no. 1 purpose be image thumbnail script, with query parameters for max- width & height, URI (relative & absolute local server URI’s, as well as remote URL’s and if configured even file paths on server – with settings for base directory and regexp’s to filters to accept and/or deny matching paths), optionally converting to PNG or JPEG with optional settings for PNG only if originally JPEG to avoid further quality loss, only if resized (as PNG is likely to be larger w/ no benefits), to convert GIF’s to 8-bit PNG’s for smaller size, also possibly only if resized, to convert from whatever to 1-bit B/W, 2-8-bit greyscale or color and with or without using 1-bit for trasparency and so on similarly for JPEG to trade size for quality, even to GIF (for whatever reason – maybe to support transparency on ancient IE’s ;) ) – but ended up putting only couple of these to actually available on query + option for smart guess auto-decision converting to PNG32 for resized JPEG’s, PNG8 for resized GIF’s, and ignoring all other conversion options, but option to convert to JPEG from PNG or even if resized from already JPEG to place small size the highest priority in all cases. Sadly I never achieved but small part of these options coded… >:D
Two options originally planned came after all this craziness, one for remote URL (really not separate option, just added setting referer to domain address of the URL) and lastly setting custom referer separately.
What I have wondered, just out of curiosity – is there any way, other than blacklisting known IP’s using scripts like this, to identify and block this kind of tools without also blocking legitimate visitors with browser set to not send referer or using anonymous proxy network, such as Tor?
Great tut.Always helpful to visit this iste