FREE THOUGHT · FREE SOFTWARE · FREE WORLD

Home » Htaccess » Htaccess Rewrites – Rewrite Tricks and Tips

Htaccess Rewrites – Rewrite Tricks and Tips

Htaccess Rewrites – Rewrite Tricks and Tips Detailed .Htaccess rewrites, Mod_Rewrite Tricks and Tips

Htaccess Rewrites – Rewrite Tricks and Tips

April 10th, 2011

Contents

  1. Htaccess rewrites TOC
  2. .htaccess rewrite examples should begin with:
  3. Require the www
  4. Loop Stopping Code
  5. Cache-Friendly File Names
  6. SEO friendly link for non-flash browsers
  7. Removing the Query_String
  8. Sending requests to a php script
  9. Setting the language variable based on Client
  10. Deny Access To Everyone Except PHP fopen
  11. Deny access to anything in a subfolder except php fopen
  12. Require no www
  13. Check for a key in QUERY_STRING
  14. Removes the QUERY_STRING from the URL
  15. Fix for infinite loops
  16. External Redirect .php files to .html files (SEO friendly)
  17. Internal Redirect .php files to .html files (SEO friendly)
  18. block access to files during certain hours of the day
  19. Rewrite underscores to hyphens for SEO URL
  20. Require the www without hardcoding
  21. Require no subdomain
  22. Require no subdomain
  23. Redirecting WordPress Feeds to Feedburner
  24. Only allow GET and PUT Request Methods
  25. Prevent Files image/file hotlinking and bandwidth stealing
  26. Stop browser prefetching
  27. Directives
  28. htaccess Guide Sections

Htaccess Rewrites are enabled by using the Apache module mod_rewrite, which is one of the most powerful Apache modules and features availale. Htaccess Rewrites through mod_rewrite provide the special ability to Rewrite requests internally as well as Redirect request externally.

When the url in your browser's location bar stays the same for a request it is an internal rewrite, when the url changes an external redirection is taking place. This is one of the first, and one of the biggest mental-blocks people have when learning about mod_rewrite... But I have a secret weapon for you to use, a new discovery from years of research that makes learning mod_rewrite drastically quicker and easier. It truly does or I wouldn't be saying so in the introduction of this article.

Despite the tons of examples and docs, mod_rewrite is voodoo. Damned cool voodoo, but still voodoo.
-- Brian Moore

Note: After years of fighting to learn my way through rewriting urls with mod_rewrite, I finally had a breakthrough and found a way to outsmart the difficulty of mod_rewrite that I just couldn't seem to master. The Mod_Rewrite RewriteCond/RewriteRule Variable Value Cheatsheet is the one-of-a-kind tool that changed the game for me and made mod_rewriting no-harder than anything else.

So keep that mod_rewrite reference bookmarked and you will be able to figure out any RewriteRule or RewriteCond, an amazing feat considering it took me a LONG time to figure this stuff out on my own. But that was before the craziness, one of the most challenging and productive .htaccess experiments I've done... An experiment so ILL it's sick like a diamond disease on your wrist! $$$. That mod_rewrite experiment/tutorial was the culmination of many different advanced mod_rewrite experiments I had done in the past and included most of my very best .htaccess tricks. With the cheatsheet it's no longer Voodoo.. Its just what you do. Now lets dig in!

Htaccess rewrites TOC


If you really want to take a look, check out the mod_rewrite.c and mod_rewrite.h files.

Be aware that mod_rewrite (RewriteRule, RewriteBase, and RewriteCond) code is executed for each and every HTTP request that accesses a file in or below the directory where the code resides, so it's always good to limit the code to certain circumstances if readily identifiable.

For example, to limit the next 5 RewriteRules to only be applied to .html and .php files, you can use the following code, which tests if the url does not end in .html or .php and if it doesn't, it will skip the next 5 RewriteRules.


RewriteRule !\.(html|php)$ - [S=5]
RewriteRule ^.*-(vf12|vf13|vf5|vf35|vf1|vf10|vf33|vf8).+$ - [S=1]

.htaccess rewrite examples should begin with:

Options +FollowSymLinks
 
RewriteEngine On
RewriteBase /

Require the www

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.askapache\.com$ [NC]
RewriteRule ^(.*)$ http://www.askapache.com/$1 [R=301,L]

Loop Stopping Code

Sometimes your rewrites cause infinite loops, stop it with one of these rewrite code snippets.

RewriteCond %{REQUEST_URI} ^/(stats/|missing\.html|failed_auth\.html|error/).* [NC]
RewriteRule .* - [L]
 
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [L]

Cache-Friendly File Names

This is probably my favorite, and I use it on every site I work on. It allows me to update my javascript and css files in my visitors cache's simply by naming them differently in the html, on the server they stay the same name. This rewrites all files for /zap/j/anything-anynumber.js to /zap/j/anything.js and /zap/c/anything-anynumber.css to /zap/c/anything.css

RewriteRule ^zap/(j|c)/([a-z]+)-([0-9]+)\.(js|css)$ /zap/$1/$2.$4 [L]

SEO friendly link for non-flash browsers

When you use flash on your site and you properly supply a link to download flash that shows up for non-flash aware browsers, it is nice to use a shortcut to keep your code clean and your external links to a minimum. This code allows me to link to site.com/getflash/ for non-flash aware browsers.

RewriteRule ^getflash/?$ http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash [NC,L,R=307]

Removing the Query_String

On many sites, the page will be displayed for both page.html and page.html?anything=anything, which hurts your SEO with duplicate content. An easy way to fix this issue is to redirect external requests containing a query string to the same uri without the query_string.

RewriteCond %{THE_REQUEST} ^GET\ /.*\;.*\ HTTP/
RewriteCond %{QUERY_STRING} !^$
RewriteRule .* http://www.askapache.com%{REQUEST_URI}? [R=301,L]

Sending requests to a php script

This .htaccess rewrite example invisibly rewrites requests for all Adobe pdf files to be handled by /cgi-bin/pdf-script.php

RewriteRule ^(.+)\.pdf$  /cgi-bin/pdf-script.php?file=$1.pdf [L,NC,QSA]

Setting the language variable based on Client

For sites using multiviews or with multiple language capabilities, it is nice to be able to send the correct language automatically based on the clients preferred language.

RewriteCond %{HTTP:Accept-Language} ^.*(de|es|fr|it|ja|ru|en).*$ [NC]
RewriteRule ^(.*)$ - [env=prefer-language:%1]

Deny Access To Everyone Except PHP fopen

This allows access to all files by php fopen, but denies anyone else.

RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^.+$ [NC]
RewriteRule .* - [F,L]

If you are looking for ways to block or deny specific requests/visitors, then you should definately read Blacklist with mod_rewrite. I give it a 10/10

Deny access to anything in a subfolder except php fopen

This can be very handy if you want to serve media files or special downloads but only through a php proxy script.

RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+)/.*\ HTTP [NC]
RewriteRule .* - [F,L]

Require no www

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^askapache\.com$ [NC]
RewriteRule ^(.*)$ http://askapache.com/$1 [R=301,L]

Check for a key in QUERY_STRING

Uses a RewriteCond Directive to check QUERY_STRING for passkey, if it doesn't find it it redirects all requests for anything in the /logged-in/ directory to the /login.php script.

RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} !passkey
RewriteRule ^/logged-in/(.*)$ /login.php [L]

Removes the QUERY_STRING from the URL

If the QUERY_STRING has any value at all besides blank than the?at the end of /login.php? tells mod_rewrite to remove the QUERY_STRING from login.php and redirect.

RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} .
RewriteRule ^login.php /login.php? [L]

Fix for infinite loops

An error message related to this isRequest exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.or you may seeRequest exceeded the limit,probable configuration error,Use 'LogLevel debug' to get a backtrace, orUse 'LimitInternalRecursion' to increase the limit if necessary

RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [L]

External Redirect .php files to .html files (SEO friendly)

RewriteRule ^(.*)\.php$ /$1.html [R=301,L]

Internal Redirect .php files to .html files (SEO friendly)

Redirects all files that end in .html to be served from filename.php so it looks like all your pages are .html but really they are .php

RewriteRule ^(.*)\.html$ $1.php [R=301,L]

block access to files during certain hours of the day

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
# If the hour is 16 (4 PM) Then deny all access
RewriteCond %{TIME_HOUR} ^16$
RewriteRule ^.*$ - [F,L]

Rewrite underscores to hyphens for SEO URL

Converts all underscores "_" in urls to hyphens "-" for SEO benefits... See the full article for more info.

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
 
RewriteRule !\.(html|php)$ - [S=4]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4-$5 [E=uscor:Yes]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4 [E=uscor:Yes]
RewriteRule ^([^_]*)_([^_]*)_(.*)$ $1-$2-$3 [E=uscor:Yes]
RewriteRule ^([^_]*)_(.*)$ $1-$2 [E=uscor:Yes]
 
RewriteCond %{ENV:uscor} ^Yes$
RewriteRule (.*) http://d.com/$1 [R=301,L]

Require the www without hardcoding

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.[a-z-]+\.[a-z]{2,6} [NC]
RewriteCond %{HTTP_HOST} ([a-z-]+\.[a-z]{2,6})$     [NC]
RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]

Require no subdomain

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} \.([a-z-]+\.[a-z]{2,6})$ [NC]
RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]

Require no subdomain

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} \.([^\.]+\.[^\.0-9]+)$
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

Redirecting WordPress Feeds to Feedburner

Full article:Redirecting WordPress Feeds to Feedburner

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^/feed\.gif$
RewriteRule .* - [L]
 
RewriteCond %{HTTP_USER_AGENT} !^.*(FeedBurner|FeedValidator) [NC]
RewriteRule ^feed/?.*$ http://feeds.feedburner.com/apache/htaccess [L,R=302]
 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Only allow GET and PUT Request Methods

Article: Request Methods

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_METHOD} !^(GET|PUT)
RewriteRule .* - [F]

Prevent Files image/file hotlinking and bandwidth stealing

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?askapache.com/.*$ [NC]
RewriteRule \.(gif|jpg|swf|flv|png)$ /feed/ [R=302,L]

Stop browser prefetching

RewriteEngine On
SetEnvIfNoCase X-Forwarded-For .+ proxy=yes
SetEnvIfNoCase X-moz prefetch no_access=yes
 
# block pre-fetch requests with X-moz headers
RewriteCond %{ENV:no_access} yes
RewriteRule .* - [F,L]

This module uses a rule-based rewriting engine (based on a regular-expression parser) to rewrite requested URLs on the fly. It supports an unlimited number of rules and an unlimited number of attached rule conditions for each rule, to provide a really flexible and powerful URL manipulation mechanism. The URL manipulations can depend on various tests, of server variables, environment variables, HTTP headers, or time stamps. Even external database lookups in various formats can be used to achieve highly granular URL matching.

This module operates on the full URLs (including the path-info part) both in per-server context (httpd.conf) and per-directory context (.htaccess) and can generate query-string parts on result. The rewritten result can lead to internal sub-processing, external request redirection or even to an internal proxy throughput.

Further details, discussion, and examples, are provided in the detailed mod_rewrite documentation.

Directives

If you aren't already comfortable using mod_rewrite then I recommend this excellent mod_rewrite guide by one of my favorite mod_rewrite gurus that I've met.


htaccess Guide Sections

| .htaccess Tutorial Index |


http://www.askapache.com/htaccess/modrewrite-tips-tricks.html#comments

Reader Comments

  1. Gunjan ~November 4, 2011 @ 3:53 am
    The "Rewrite underscores to hyphens for SEO URL" is really good one.
  2. ken shoufer ~October 26, 2011 @ 12:13 pm
    Good information for web site security. I will try to put it into practice soon. Thanks very much.
  3. sergio ~October 6, 2011 @ 7:38 am
    it would be cool if you add an example to ALWAYS find findme.html regardless of where it was requested to be, like an .app is executed no matter where the document is calling for it. If it's with just a regex I'd help me with the following: I wrote a regex for a rewrite rule that includes a negative lookahead to replace the rewriteCond line, because WordPress only accepts two values: pattern -> substitution. No conditionals. It should find findme.html _here, regardless of where it's requested to be: mydomain.com/_here/findme.html e.g. (Sorry, I can't modify the swf which will request findme.html in the wrong places) So, given findme.html could be requested to be in, e.g. (always in the same directory than the page that called it):
    mydomain.com/findme.html
    mydomain.com/directory/findme.html
    mydomain.com/directory/subdirectory/findme.html?someparam=3
    The rewrite should make them all (query string could stay, though)
    mydomain.com/_here/findme.html
    So, I made a rewrite rule that WordPress will accept, with a negative lookahead so it only matches URLs which dont contain "_here/" already, as follow
    Options +FollowSymlinks
    RewriteEngine On
    RewriteRule ^.*?(?!_here/)findme\.html$ /_here/findme.html [R=301,L]
    The problem is it LOOPS. What did I miss? (I tested it with no other code in the .htaccess file, still looping)
  4. Thomas [TA] ~September 24, 2011 @ 2:29 pm

    You saved my day!!!

    Trying for several houres to do the impossible: getting rid of index.php while also having to internally redirect some uris to use index.php prepended. I ended up in infinite loops but your page showed me how to stop further rules processing when the page REDIRECT_STATUS got 200! Thanks for the great work. Really worth a bookmark!

  5. Kellie ~September 16, 2011 @ 5:01 pm
    Hey All, Currently, we installed Drupal on a hosted server with a subdomain. http://apps.domain.com/drupal is it's path. But, we'd like for it to go to http://www.mynewdomain.com I do not want the customers to see the working domain (http://apps.domain.com/drupal) but rather the new domain (http://www.mynewdomain.com). Any ideas or suggestions?
  6. John ~July 7, 2011 @ 1:37 pm
    Thanks. Looking all day for something like your cache friendly file names. great solution, just what I needed.
  7. Lostmon ~June 28, 2011 @ 7:42 pm
    Thnx for this MASTER Class !! it has helped me so many times !!!!!
  8. Sandra ~May 22, 2011 @ 7:51 pm
    Hello. I hope you can give me a hint on how to fix the following: I want any requests with any extra "words" [paths] (e.g., www.mydomain.com/words/index.html, etc.) just to be directed to my "index" page which I have redirected to/. If the word "index" is in the url, I want the page to be direct to the /. I have only one domain on the server. I want any requests (e.g., "word", "paper", "text", "any words") that is (are) entered where "word" is in the above example to be redirected to/ . Presently I have:
    RewriteCond %{THE_REQUEST} ^.*/index\.html
    RewriteRule ^(.*)index.html$ http://www.mydomain.com/$1 [R=301,L]
    I have tried many variations of the above--with the same results or a 500 error. It redirects pages that have index.html in the url, but not pages that may have variants [additional paths]like: www.mydomain.com/words/index.html. In other words, somebody that may be looking for an index on the page "words" types this in their browser to look for the "index" of the "words" page. They should go to www.mydomain.com/. Instead, it directs to the real page if it exists, but just shows text--not pics and other items on the page. Again, I don't want a partial page display, just redirected to the index page, which is /.
  9. ramesh ~May 7, 2011 @ 7:55 am
    thanks Man!!! perfect tutorial
  10. Colin ~April 19, 2011 @ 6:15 am
    I've redesigned a website and moved it from windows hosting to Linux, the old site had .aspx pages and the new site has .htm pages I would like to use mod rewrite to redirect using 301, my attempts so far have not worked, can you please help?
    old site pages = site.com/contact.aspx
    new site pages =site.com/contact.htm
    Thanks
  11. AskApache ~April 15, 2011 @ 2:44 pm
    You will need to use the value of another variable. For instance you can use 2 RewriteRules, the 1st one to save a few digits from the output of %TIME and the 2nd one to rewrite the dir using that value. Not really random but good.
  12. Ali Muaviah ~April 13, 2011 @ 4:08 am
    I really want to generate a random directory name in the URL with .htaccess, is it possible?
       1. www.mywebsite.com
       2. .htaccess redirects to
       3. www.mywebsite.com/.FB4/
    so, I want to generate this ".FB4" string randomly for each request (directory names aren't generated in advanced, so I need to pick randomly. I just want to create that string randomly). but how? thanks for your help.
  13. Thomas ~April 1, 2011 @ 3:57 pm
    If i have now a blog on wordpress .. domain/%year%/%monthnum%/%day%/%postname%/ and i've changed the permalinks to domain/%postname%/ how can i make the redirect 301 ?
  14. iconus ~March 29, 2011 @ 9:19 am
    Thanks for the tutorial, I feel like I've tried everything so I'll post here. I want to go from a /folder/ to /folder/file.php I tried all kinds of commands in the httaccess file with now success, can you help? Every time I go to site.com/dir/ I want it to go directly to site.com/dir/login_page.php thanks!
  15. Sumit Kumar ~March 28, 2011 @ 2:59 pm
    Hi, I am looking for .htaccess 301 redirect for a query string to subdomain like www.example.com?index.php?option=subdomain which I need to redirect on subdomain.example.com. Please help me. Thanks
  16. Danilo ~March 17, 2011 @ 2:38 pm
    Hi. I'm a user of Joomla and i want to remove the article ID from the URL so site.com/dir/a/b/120-adesivo-ttt -> site.com/dir/a/b/adesivo-ttt These are the lines of rewrite rules on my .htaccess file:
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/index.php
    RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$  [NC]
    RewriteRule (.*) index.php
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
    Note tha i've already activate rewrite rule so the urls of articles become more friendly. But i still want to remove this piece of the URL. Thanks.
  17. Angelon ~March 16, 2011 @ 2:06 am
    wow.. thank u soo much.. this information really helped me
  18. sumit ~March 15, 2011 @ 6:19 am
    hello, no man its not working is that any other idea to let me out of this.........
  19. Webmonkey ~March 12, 2011 @ 6:33 pm
    I'm new to trying to do anything fancy with htaccess. I have a site that has a number of files in different directories, eg.
    http://site.com/directory1/342.shtml
    http://site.com/directory2/221.shtml
    http://site.com/directory3/455.shtml
    Sometimes, an item gets sold and gets moved into a new directory, but the filename says the same, so for the above three examples, the new address looks like this:
    http://site.com/sold-item/342.shtml
    http://site.com/sold-item/221.shtml
    http://site.com/sold-item/455.shtml
    So when someone clicks on a previously indexed link in Google, they'll get a 404. There are too many pages to do this with 301 redirects, eg., the RedirectPermanent command. I want a conditional rewrite so that if a file is not found in one of the directories, the server checks the /sold-item/ directory for the same file name, and if it's found, sends the browser request there. So firstly, how do those RewriteEngine commands look? As far as I can work out, the query should start with these two lines:
    RewriteEngine on
    RewriteCond %{SCRIPT_FILENAME} !-f
    Then I've been trying a third line along the lines of
    RewriteRule  ^(.+)  http://site.com/sold-item/%$1 [R=301,L]
    Of course this isn't working. Finally, three quick questions:
    1. Do I then need to close this out with a "RewriteEngine off" command?
    2. Do I need to put one .htaccess file in each of the directories or can I run it from the main one in the root directory?
    3. Will all the pre-existing Redirect Permanent entries and the defined 404 error file in my root directory .htaccess file continue to work as before?
    Thanks for any help that can be given!
  20. raghu ~March 11, 2011 @ 11:24 am
    need some help here We need to create a redirect using the httpd.conf file which redirects users coming into base url using http to https. http://xxx.com -> https://xxx.com If there is anything after the base url we need to let the request go through without redirecting. For example: http://xxx.com/status.html should not be redirected.
  21. kuko ~March 1, 2011 @ 5:01 pm
    hi; anyone can help plz? how can i do a rewrite from subdird.domain.ltd internaly to domain.ldt/index.php? the structure looks like this on my hosting:
    /root_www/index.php (we want to rewrite from 3th lvl domain to this)
    /subdird/
    so when i access in browser subdir.domain.ltd/ it rewrites internaly to domain.ltd/index.php
  22. Ciges ~February 22, 2011 @ 11:06 am
    Great article! Thanks to your mod_rewrite guide I have resolved one configuration's question. For future needs I will have your guide as reference :-)
  23. Markus ~February 18, 2011 @ 12:55 am
    Some worked great, but found one for my needs, had to remove the html completely and replace with an "/" wordpress style
  24. John ~February 10, 2011 @ 2:50 pm
    I am wanting to set up multi sites in WordPress with http://site.com/reviews/ being my main site and having several sites off of it. I am trying to set up http://site.com/tents but no theme shows - only written material. Then when I try to log on from that page, I get the message - "Apologies, but the page you requested could not be found. Perhaps searching will help." . I put an html index on the site and it works. How do I determine what is needed to make the php index work? Thank you, John
  25. Vijay Gupta ~February 10, 2011 @ 5:52 am
    Hi, We are seo url rewriting on our site but that url took some in the url but we wanted remove this type of id's and numbers from the url with the help of seo url rewriting. Still we are getting like this http://www.site.com/motorola-xt720-p-790.html and we wanted like this http://www.site.com/motorola-xt720.html where motorola-xt720 is the products name we are using cre loaded. Thanks in advance. any one can help me regarding to this...?
  26. Ivo ~February 7, 2011 @ 3:54 am
    Hi, I have a problem with SEO link and browse folder: I have this situation: If URL is: mysite/something I call ser.php?action=$1 mysite/something/somethingElse I call serv.php?action=$1&subaction=$2 This works fine but, my problem is if I want browse folder "TEST" mysite/TEST How to configure .httaccess to browse "TEST" but if "TEEST" to call ser.php?action=$1 Below is my .htaccess
    Options +FollowSymlinks
    Options +Indexes
    RewriteEngine On
    RewriteCond %{REQUEST_URI} ^(.*)TEST [NC]
    RewriteRule ^(.*)$ http://localhost/$1 [R=301,L]
    RewriteCond %{REQUEST_URI} ^(.*)TEST/ [NC]
    RewriteRule ^(.*)$ http://localhost/$1 [R=301,L]
     
    Options +FollowSymLinks
    DirectoryIndex main.php
    RewriteEngine On
    #RewriteBase /
    ErrorDocument 404 /404.php
    RewriteRule ^index\.(.*)$ main.php
    RewriteRule ^([a-zA-Z-_0-9]+)$ ser.php?action=$1
    RewriteRule ^([a-zA-Z-_0-9]+)/$ ser.php?action=$1
    RewriteRule ^([a-zA-Z-_0-9]+)/([a-zA-Z-_0-9]+)$ serv.php?action=$1&subaction=$2
    RewriteRule ^([a-zA-Z-_0-9]+)/([a-zA-Z-_0-9]+)/$ serv.php?action=$1&subaction=$2
  27. TexasExplorer ~January 31, 2011 @ 12:18 am
    I have a shopping cart which requires one rewrite, and I have WordPress that needs a rewrite rule for path names, and I have a rewrite rule that directs mydomain.com to www.mydomain.com. The problem is, when the WordPress code is there, the shopping cart rewrite rule doesn't work. Is there a way I can do this and still be able to keep all the rewrite rules? Thanks in advance =).
    RewriteEngine On
     
    RewriteCond %{REQUEST_URI} !-s
    RewriteRule ^page/(.*) /Merchant2/merchant.mvc?page=$1
    php_flag register_globals on
     
    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP_HOST} ^mydomain.com$ [NC]
    RewriteRule (.*) [mydomain.com...] [R=301,L]
     
    # BEGIN WordPress
     
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
     
    # END WordPress
  28. Tig ~January 20, 2011 @ 11:56 am
    Yeah, great article. Have it bookmarked for about an year now, and still coming back to it for further notices ... awesome.
  29. Prasanna ~January 17, 2011 @ 3:24 am
    Hi, How can I clean out query string from url accessing the default page. e.g http://www.site.com/?id=123 or http://www.site.com/?a=b&c=d All of such hits to be redirected to http://www.site.com/ I could achieve this for the case when index.php is present but not when index.php is ommitted. help?
    RewriteCond %{REQUEST_URI} ^/(index\.php).*
    RewriteRule ^(.*)$ http://www.site.com/? [R=301,L]
  30. omar ~January 15, 2011 @ 4:54 am
    thinks
  31. SuperZ ~December 28, 2010 @ 4:56 pm
    What a brilliant write up on this complicated issue. I've been trying to search on how to silently redirect dynamic sub domains (non-existent subdomains but using wildcards) to a folder on the TLD. e.g. when a user types in http://subdomain.domain.com/ they actually see this address on the page http://domain.com/subdomain/ (but the address stays like "http://subdomain.domain.com/" ) What I currently have at the moment is this .htaccess code below:
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+)\.domain\.com$ [NC]
    RewriteRule ^(.*)$ http://domain.com/$1 [L]
    Is this the correct way of achiveing what I need?
  32. lichti666 ~December 26, 2010 @ 6:20 pm
    Hi, I need following help for Rewrite Url: Input:
    http://domain.de/test.php/
    should redirect to
    http://domain.de/test.php
    Can anybody help me to create the right rewrite rule and condition? Thanks a lot.
  33. amit ~December 18, 2010 @ 9:03 am
    It is a very helping post. Thanks to all first. I have a problem. http://www.site.com/domainUrl-com. But i want output like http://www.site.com/domainUrl.com. Can anyone help me to resolve this problem
  34. Tadi ~December 13, 2010 @ 4:48 pm
    Hi, i had a url site.com\Bussiness\xxxxxxxxxxxxx when someone hits the url site.com\xxxxxxxxxxx it should redirect to site.com\Bussiness\xxxxxxxxxxxxx even though i skip /Bussiness. what is the rewrite rule for that
  35. amsaraj ~November 18, 2010 @ 4:50 am

    consider this case: http://local/new/node/4?task=view&s=negol

    I want to rewrite it as http://local/new/negol

    What are the possiblities to put double condition of "task" and "s" ?

  36. Luat Nguyen ~November 14, 2010 @ 12:41 pm

    Why don't it run link http://localhost/content/abc.php when the executing I has received the notice is not found file. :|. why?

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

    I want exec file abc.php. but not found it.

  37. Bob ~October 30, 2010 @ 12:27 pm
    This problem has me stumped. My original site was written in html, the index page in public_html was index.html I have hundreds of incoming links to site.com/index.html I am now using joomla and the index page is index.php, I needed to do a 301 from index.html to http://site.com/ I have the site setup to remove the index.php from the url which is working, however, when I add the following 301,
    Redirect 301 /index.html http://site.com/index.php
    it changes my home page url back to http://site.com/index.php It is clear to see that this is happening because the 301 is telling it to do so, however, I can find no way to do the 301 without including the index.php Any ideas?
  38. Dale ~October 28, 2010 @ 8:35 am
    A problem with wordpress
    # BEGIN WordPress
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
     
    # uploaded files
    RewriteRule ^([_0-9a-zA-Z-]+/)?files/(.+) wp-includes/ms-files.php?file=$2 [L]
     
    # add a trailing slash to /wp-admin
    RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
     
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    RewriteRule  ^[_0-9a-zA-Z-]+/(wp-(content|admin|includes).*) $1 [L]
    RewriteRule  ^[_0-9a-zA-Z-]+/(.*\.php)$ $1 [L]
    RewriteRule . index.php [L]
    # END WordPress
    The problem is that we set permalink rewrite http://domain.com/subdirectory/%categories%/%postname%/... but it's not working
    400 BAD REQUEST ERROR
    result is http://domain.com/subdirectory/subdirectory/%categories%/postname/ Any suggestions welcome
  39. Julian ~October 27, 2010 @ 10:11 am
    Hi, I recently redesigned my site to use urls like www.domain.com/page.htm instead of www.domain.com/index.php?p=page.php What I want to do now is to create a rewriterule in htaccess that redirects the old url format to the new one. So, I want to get the page name from the p variable in the query string, change the extension to htm and then redirect to the page name plus htm. I was thinking that I might be able to do this with the following but it doesn't work.
    RewriteCond %{QUERY_STRING} ^p=(.*)\.php$ [NC]
    RewriteRule ^index\.php$ http://www.domain.com/$1.htm [R=301,NC,L]
    Any assistance or pointers on how to do this would be most appreciated. Thanks, Jules
  40. michael ~October 16, 2010 @ 5:57 am
    Hi, Before an upgrade to my powweb.com web hosts server I was using the following directive to phrase .php files as .htm files for SEO. However, after the upgrade to Apache 2.0 and the rewrite module it has rendered the following useless;
    RewriteEngine on
    RewriteBase /somedir
    RewriteRule ^somepage\.htm$ somepage.php [T=application/x-httpd-php] 
    Any ideas how to get the .php files reading as .htm again ???
  41. Severin ~October 6, 2010 @ 2:08 pm
    Great post, thanks i would like expand my actual htaccess. actual i have:
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule .* index.php [L]</acronym>
    in my htaccess. But for Analytics and Maps its better when I have only http:www url's an. i have tested these nice script, but it those not work:
    Options +FollowSymLinks
    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP_HOST} !^www\.[a-z-]+\.[a-z]{2,6} [NC]
    RewriteCond %{HTTP_HOST} ([a-z-]+\.[a-z]{2,6})$     [NC]
    RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]
    I would like a htaccess script how rewrite all times my different url's to http://www.xxxxx i have any one a idea why i can fix my bug? Best Regrads Severin
  42. rahat ~September 8, 2010 @ 5:24 am
    i want to add a page automatically to user made directory like giving it a new URL on the site so if any one can help me on this
  43. ash ~August 31, 2010 @ 3:03 am
    excellent post....thanks :)
  44. perochak ~August 22, 2010 @ 2:50 am
    Hi, I am looking for HTaccess code for Pagination. I have the url as http://site.com/article.php?do=read&amp;page=5 Any one can help?? Regards Perochak
  45. Jerome Bailey ~August 21, 2010 @ 12:10 pm
    this was good and helpful man. keep it up. one concern though, when i tried to use the rule to rewrite hyphens to underscores, images on a particular page were not showing up, do you know why?
  46. Thomas ~August 21, 2010 @ 7:46 am
    Hi, "Require the www without hard coding" does not work, any solutions???
    Options +FollowSymLinks
    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP_HOST} !^www\.[a-z-]+\.[a-z]{2,6} [NC]
    RewriteCond %{HTTP_HOST} ([a-z-]+\.[a-z]{2,6})$     [NC]
    RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]
  47. mejrel ~August 10, 2010 @ 12:44 pm
    hi my htaccess file works ok when i enter parameters manually on address bar but i want to redirect to that url permanently. How can i do that please help.. My htaccess file look like this:
    RewriteEngine On
    RewriteRule ^catalog-([^-]*)-([^-]*)-([^-]*)-([^-]*)\.html$ /s_list.php?loc=$1&amp;type=$2&amp;price1=$3&amp;price2=$4 [L]
  48. SALIM ~July 28, 2010 @ 9:47 am
    Hi friends: Instead of having this URL : www.site.com:8080/m.php I want to hide only the port and the URL will be like this: www.site.com/m.php What I do to resolve this problem. Thanks a lot for your response
  49. wyrmmage ~July 27, 2010 @ 6:17 pm
    The "Make a prefetching hint for Firefox." link goes nowhere, because the section is not present in the page.
  50. BrianMI ~July 6, 2010 @ 3:01 pm
    This tutorial was helpful, but I'm not able to get a rewrite done on my site. In essence here is what I want to happen: 301 redirect http://sub.domain.com/tag/t/ …to… http://domain.com/tag/t/ Can anyone share how to do this exactly? (this is all on a wordpress site)
  51. Irfan Suleman ~July 6, 2010 @ 5:31 am
    awesome, thanks
  52. Snehasis Mohapatra ~June 30, 2010 @ 12:58 am
    Below lines are used to redirect anything in the URl after the domain to a single file . 1st two lines are used to block the URL used regularly for including CSS/JS these such files and the 3rd one is to redirect all urls to a single PHP file.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)+$ yourfile.php [NC]
    Hope this may help you in any way. Thanks
  53. Vikram ~June 23, 2010 @ 7:06 am
    Hi! I knew about skip functionality in htaccess from this post and it solved my big problem on which I spend 2hrs. Thank you. Thank you very much. Vikram India
  54. Roman ~June 16, 2010 @ 3:12 pm
    Leslie wrote:

    I have a WordPress site and am using:

    RedirectMatch 302 /download/example(.*) http://example.com/id=1234&amp;profile=54321$1

    for redirects in my .htaccess file to my affiliate links but everything seems to go horribly wrong when using ampersands in my redirected urls and they are required in many instances. Anyone have any ideas on how to fix this?

    Try escaping ampersands with a back slash. I've had the same problem, and that's how I've solved it.
  55. Earneste ~June 9, 2010 @ 11:24 am
    I have a lot of duplicate pages created with query strings such as this site.com/?fg25f656 or site.com/folder/file.php?25d6562d There are no equal signs in the query strings. I have done a extensive search can not find the source of this. Google somehow sees these url with query strings but i can't How can i used mod rewrite to remove them? I used the following below but it does not seem to work
    RewriteCond %{THE_REQUEST} ^GET\ /.*\;.*\ HTTP/
    RewriteCond %{QUERY_STRING} !^$
    RewriteRule .* http://www.apache.com%{REQUEST_URI}? [R=301,L]
  56. Philippe ~June 2, 2010 @ 9:42 am
    thanks, good tutorial If I use your code for Cache-Friendly File Names, is it going to create 301 redirects or is it Apache internal rewrite? thank you, Philippe
  57. revanth ~June 2, 2010 @ 1:51 am
    Hello, I have used url rewrite to my site, and in my site I have a page products.php I used it to redirect to rewrite.html and it is working fine. But the client wants to redirect the site to the same page i.e, rewrite.html if he hard codes the URL. Also i.e, if he directly types the URL in the browser please give me solution.
  58. Alessio ~May 29, 2010 @ 2:15 am
    How to get read of the ID? i have site.com/forums/8-A-k There are 2 Things i would like to achieve:
    1. Most important is getting read of the id "8"
    2. Might be able to figure out myself, just want to have a slash instead of a filetype at the end. Like: site.com/forums/8-A-k /
    This would be the goal, no id, nice slash. Any help highly appreciated.
  59. tonilony ~May 25, 2010 @ 3:08 pm
    Hi. I use the free CMS Joomla for my websites. Now I changed my .htaccess for removing the query_string. Unfortunately Joomla uses in the back-end the query_string for different options. This looks like: site.com/administrator/index.php?option=com_menus. Therefore I would like to exclude this url/folder from removing the query_string. I would really appreciate your help. Thanks, Toni
  60. pera webbhotell ~May 25, 2010 @ 1:38 pm
    Hi I need a RewriteCond that will take
    http://site.se/site.se
    site.se is any domain that must end with .se and then a RewriteRule to get it like this
    http://site.se/order/domainchecker.php?domain=site&amp;amp;tlds[]=.se
    have been trying some days now....
  61. Abhi ~May 18, 2010 @ 5:09 pm
    I was reading and i just cant understand which line to use?
    RewriteCond %{HTTP_HOST} ^domain.com [NC]
    RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,NC]
    RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
    RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,NC]
    Both seem to work ok?
  62. Ali Honari ~May 18, 2010 @ 9:37 am
    hello! I have 5 landing pages and I want .htaccess code for this: Sample 5 pages Landing URLs Examples:
    www.site.com/pt/
    www.site.com/mbc/
    www.site.com/it/
    www.site.com/ea/
    www.site.com/fq/
    (pt,mbc,it,ea,fq are folders and all are having own index.php file) I want to put that kind of URLs on net (for craiglist , facebook etcc. for advertisments purpose.)
    www.site.com/pt/Facebook_ad_5
    if any access above URL it should be back to
    www.site.com/pt/index.php
    FYI: Facebook_ad_5 is any word, where i ll place the i ll leave links but it should be redirect to the index.php of the folder. Thanks for help.
  63. sweta makode ~May 13, 2010 @ 2:05 am
    Hello, In my website I used the url like www.site.com/user/page.php which i had done using mod_rewrite in .htaccess file,originally the url is like www.site.com?uid =user&amp;pid=page.php, but now the client had asked me for the url like www.user.site.com/page.php , is it possible to get it done by URL mapping and using the concept of virtual subdomain or I have to introduce the concept of subdomains creation in my website to get it done. Please reply asap. Thankyou.
  64. movers ~May 12, 2010 @ 1:17 am

    Excellent information, lots of helpful tips, I have been racking my brain trying to find ways to do this, and then I found askapache!

  65. Priya ~May 5, 2010 @ 7:39 am

    Hi,

    I want to direct www.user1.site.com to www.site.com/user1/

    I will be having the folder user1 in root. Can anyone suggest an htaccess rewrite for this?

    Thanks

  66. Php Resources ~April 22, 2010 @ 2:47 am
    I found rewriting on my site with same using hyphen
  67. Phil ~April 15, 2010 @ 9:14 pm

    Shouldn't the "Internal Redirect .php files to .html files (SEO friendly)" NOT have the [R] tag? otherwise, the location bar is changed, correct?

    I think that was Vector Thorn's issue as well.

  68. Peter Bearseley ~April 15, 2010 @ 5:01 am
    Hi Guys, Please advise me with the following redirect request?
    From
    http://www.site.com/lbr_ss?action=go_generic_link&amp;amp;category=SPORTS&amp;amp;level=CLASS&amp;amp;key=0037
    To
    http://sports.site.com/en-gb/Specials-2086
    Any help much appreciate it. Thanks, Peter
  69. argh ~April 6, 2010 @ 1:35 pm
    I stopped caring about the content of this site the moment it started to play music. No, I don't want that to happen unless I press "play" somewhere.
  70. stu ~April 2, 2010 @ 11:45 am
    hey, so... How to redirect all traffic to a subdirectory on a site to another page, **without** using mod_rewrite:
    RedirectMatch 301 /catalog/(.*)$ http://www.example.com/
    In the above example, all traffic to the /catalog/ directory is redirected to / (the homepage). This is equivalent to the above:
    RedirectMatch 301 /catalog/(.*)$ http://www.example.com/index.html
    This does a 301 (permanent redirect). 302 (temporary) is also possible.
  71. AskApache ~April 1, 2010 @ 1:42 pm
    http://www.microsoft.com/web/spotlight/urlrewriter/
  72. Jal Ulati ~March 18, 2010 @ 10:15 am
    @ IMEL IMEL wrote: "Hi, I just want to ask one question, for example: if I have website with URL address http://www.example.com/index.php?option=com_user But I just want to display URL like “http://www.example.com/“. What should I do? Thanks in advance" Imel, I also would like to know the answer to your question. It would seem to me to be a fundamental problem, and surely very simple to solve. And yet, I've searched for too long and found NO answer. How can this be? What are we missing?
  73. Wasim ~March 5, 2010 @ 3:24 am
    too good man.. i almost solved my problem of .htaccess by reading this article. just a quick question.. i am stuck on one of my requirement, here it goes .. i want to redirect any url from my website that look like this.. "www.mysite.com/detail.php?cid=12&amp;amp;cname=Website&amp;amp;mid=345&amp;amp;mname=My-Web" TO "www.mysite.com/Website/My-Web.html" would really appreciate any help from anyone :) Thanks
  74. Adnan ~March 3, 2010 @ 5:47 am
    Hi , i m having a problem , i am using cat/ambulance/12 and this is redirected to the page written in htaccess, i just want to use the same url as above. how can it be possible
  75. art.mania ~February 25, 2010 @ 4:17 pm
    Hi, very cool post!! thanks a lot!! I read all your article and tried to sort out my problem, but I'm still having trouble :/ I would appreciate you so much if you give your few minutes to see my issue; (explained at the link below) http://stackoverflow.com/questions/2319033/404-error-page-redirection-and-404-page-200-ok-header-issues I appreciate so much! I'm fighting with this issue for weeks, but couldnot make even a step :(
  76. Q ~December 17, 2009 @ 2:15 am
    Wanting to do away with .htaccess to speed server... How to move these commands to httpd.config?
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^mysite\.com
    RewriteCond %{SERVER_PORT} ^80$
    RewriteRule (.*) http://www.mysite.com/$1 [R=301,L,QSA]
    Simply moving them over doesn't work. Years ago it took me forever to figure out the above commands to help search rankings with the non www thingy.
  77. Hussain ~December 10, 2009 @ 4:29 am
    Hi i need a little bit of help. my requirement is to fix the page name with extension and variable name because i want to make my URL more short like below url OLD URL: site.com/index.php?JScript=first_JavaScript NEW URL (Required): site.com/first_JavaScript Please guide me, Regards, Hussain
  78. FMut ~December 9, 2009 @ 9:43 pm
    Nice examples... this helped heaps. I'm still having trouble doing the following; if anyone cares to guide me.. I have a PHP framework that uses root level index.php, so a typical URL will look like this: www.domain.com/index.php/argument1/argument2/etc it is simple enough to remove the index.php so the URL looks pretty, like: www.domain.com/argument1/argument2/etc Where I get stuck is trying to "replace" the index.php with a "KEYWORD" - to help with SEO... e.g. www.domain.com/KEYWORD/argument1/argument2/etc but retain the underlying URL (as far as PHP application is concerned) as www.domain.com/index.php/argument1/argument2/etc Is this possible?
  79. Vector Thorn ~November 19, 2009 @ 7:52 am
    Ah, i got it; i was using them for redirects, and now i see that by not actually redirecting you can accomplish this.
  80. Vector Thorn ~November 18, 2009 @ 6:28 pm
    With all the mod_rewrite articles out there that show you how to redirect a request, none of them show you how to keep the url in the address bar the same? For example, you say you can redirect: /somepage-1234.html to the page: /?somepage=1234 [R=301] But when you do that, the user is taken to that page, and it is shown in the address bar as the dynamic page. So how to you keep the original url in the address bar?
  81. juan fernando ~November 12, 2009 @ 1:15 am
    I have several domains point to the same htdocs directory. i have some static content that resides under htdocs/domain.com/images/blah.jpg so how do i take a request that is images/blah.jpg and properly check against htdocs/domain.com/images/blah.jpg and if the file doesn't exist then go to view.php?search=images/blah.jpg ?
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteCond %1/%{REQUEST_FILENAME} -f
    RewriteCond %1/%{REQUEST_FILENAME} -d
    RewriteRule index.php?=%{REQUEST_FILENAME} [L]
  82. Richard ~November 10, 2009 @ 3:06 pm
    Awesome job, this was the page that pulled all the pieces together for me. Thanks! Richard
  83. pilot ~October 11, 2009 @ 12:39 pm

    2nd Follow-up on REQUIRE NO SUBDOMAIN -- the other (first) prototype above

    Just a note on the other version above. It reads:

    RewriteCond %{HTTP_HOST} \.([a-z-]+\.[a-z]{2,6})$ [NC]
    RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]

    It may be worth noting that the domain name part of the filter is missing numbers. That is, the class "[a-z-]" means any lower case alphabetical character and the "-" dash symbol, but numbers can also be used in domains. I still do not see why the forward slash is placed preceding the $1 in the rewrite (see earlier comments on this). So I propose the following instead:

    RewriteCond %{HTTP_HOST} \.([a-z0-9-]+\.[a-z]{2,6})$ [NC]
    RewriteRule ^/(.*)$ http://%1$1 [R=301]
  84. pilot ~October 11, 2009 @ 12:29 pm

    Follow up to previous post about REQUIRE NO SUBDOMAIN

    I have tried the following bit of code and it seems to work in every conceivable case. I have a mixed SSL and non-SSL website with gates directing according back and forth accordingly. The Rewrite directive with the "http://..." doesnt cause problems, I think for the reasons I outlined in the previous post. Also, I run some servers on nonnormal ports for SSL (i.e., not 443) but this recipe also seems to work when explicitly detailing the port in the request (i.e., https://garbage-I-want-to-get-rid-of.myDomain.com:445/some/path ). I guess the reason is that HTTP_HOST includes the port number as part of the variable and I have NOT excluded numbers in the second negative class of the conditional (unlike in the original REQUIRE NO SUBDOMAIN above and so they do not get rewritten.

    In any case, the code I am using (successfully... so far) is:

    RewriteCond %{HTTP_HOST} \.([^.]+\.[^.]+)$
    RewriteRule ^(.*)$ http://%1$1 [R=301]

    Note also I have omitted the "L" tag -- I have and you might have further Rewrites in he same directory...

    Also note: per my previous note, I removed the backslash \ escapes from the character classes in the conditionals without problem, so I assume the original taken from here was not optimal. For comparison, the older version I am referring to reads:

    RewriteCond %{HTTP_HOST} \.([^\.]+\.[^\.0-9]+)$
    RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
  85. pilot ~October 11, 2009 @ 11:47 am

    Wonderful work/tutorial! A real pleasure to see actually how apache operates!!

    Question:

    In the second example of No Subdomains it states:

    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP_HOST} \.([^\.]+\.[^\.0-9]+)$
    RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

    Why are the "." in the classes escaped with \ ? Are not all meta characters automatically escaped in class ranges? Why or how does the "/" work in the %1/$1? Does not the $1 already include the / ? In the second class [^\.0-9] the numbers must be there for the case where a port has been identified I assume (?), because an IP address would anyway show up with 2 or more "." But then, shouldn't ":" also be included? Or did I miss something?

    As an aside, I think this also works for cases where one is alternating between SSL and otherwise if (and only if) one has further rewrites to handle where the page should be encrypted. From the tutorial I read it would seem that when authentication is processed, the returned page will be passed once through to get the domain correct, but then on the second pass will not be rewritten (as it not longer meets the conditions) and so be forced to SLL (by whatever other rewrites or redirects are present).

  86. Samson ~October 10, 2009 @ 7:23 am
    I want to add the ability to put a hyphen in the subdomain. Can I do this also with .htaccess rewrite? If so how do I code this?
  87. mathguy ~October 1, 2009 @ 12:38 pm
    Hi, Awesome information Please provide me the solution for the following. I have used the following redirection code in my .htaccess file which used to work fine in server where I hosted early.
    RewriteEngine on
    RewriteCond %{REQUEST_URI} ^/(.*).html
    RewriteRule ^(.*).html /math-tutorial/tutor.php?name=$1 [L]
    The Rewrite condition work perfectly, but not the rewrite rule. Thanks
  88. Andrew ~September 29, 2009 @ 4:26 am
    I've been trying to change php extensions to html for the last week and they simply will not abide by the rule
    RewriteBase /
    RewriteRule ^(.*)-p-(.*).html$ .php?city=$2&amp;amp;%{QUERY_STRING}
    It's dring me crazy :( Any help would be cool
  89. EJ ~August 26, 2009 @ 3:35 am
    Super htaccess article. It was a good help to me. Thanks.
  90. TrueFalse ~August 19, 2009 @ 8:04 am
    Great stuff here! However, I don't completely understand the Prevent Hotlinks example code you've given. In the code you list your domain name -- should that be MY domain name when I'm implementing? What's up with the /feed/ element? I noticed that the version at this site replaced /feed/ with /feed.gif -- I don't get it... That site also added the line
    Options +FollowSymLinks
    at the beginning of their Prevent Hotlinks example. Is that correct/needed? Thanks!
  91. jayanta ~August 12, 2009 @ 2:21 pm
    I want when a user comes to site.com, it automatically shows the content site.com/username and all the requests like site.com/profile.php?id=xxx Can anybody write that script for me, or guide me to the nearest search engine, because I can't find any search engines, and I don't know how to use google.
  92. F. Fox ~August 11, 2009 @ 3:09 am
    Great tips. All very usefull, and I needed them all! Thanks!
  93. Chuck ~July 24, 2009 @ 12:32 pm
    Excellent article, BTW. So here's my issue. I am using htaccess to do mod_rewriting for friendly URLs (in MODx CMS), but I also need to redirect all the old pages from the old site (.php files). I've been trying to use Redirect 301 directives but they fail. So I did some searching and came across a possible solution, but I have yet to make it work, hopefully you can help: I am trying to get http://example.com/page.php?jan=$1 to redirect to a url without those variables visible. Here's what I have:
    Options +FollowSymlinks
    RewriteEngine On
    RewriteBase /
    &nbsp;
    # Redirects
    RewriteRule ^page.php?jan=$1 /text-to-article [R=301,L]
    I have a list of about 100 files, not all have variables, but all are php files. Thanks :)
  94. Pollux ~July 6, 2009 @ 5:28 am
    How to simply rewrite all my .php extensions to .html. This is my .htaccess file but it is not working properly. My homepage doesn't display anymore!!
    Options +FollowSymLinks
    &nbsp;
    RewriteEngine On
    RewriteRule ^(.*)\.php$ /$1.html [R=301,L]
  95. Prasad ~June 17, 2009 @ 4:49 am
    Nice post! But It didn't help me with my issue... I am currently hosting at example.domain.com and have purchased example.com When I use mask URL for my domain forwarding, I always see example.com in the browser I want that when the 'my-post' link is clicked, the URL should show as example.com/my-post (since internal request generated is example.domain.com/my-post Can someone help me please
  96. Leslie ~June 1, 2009 @ 6:47 pm
    I have a WordPress site and am using:
    RedirectMatch 302 /download/example(.*) http://example.com/id=1234&amp;profile=54321$1
    for redirects in my .htaccess file to my affiliate links but everything seems to go horribly wrong when using ampersands in my redirected urls and they are required in many instances. Anyone have any ideas on how to fix this?
  97. monokrome ~April 9, 2009 @ 12:35 am
    You know, it's more realistic to be forcing users NOT use www instead of requiring www. The subdomain www is deprecated nowadays, since modern systems know what service you are requesting without needing a separate zone for each. Just thought this was worth mention.
  98. Rishi ~March 19, 2009 @ 4:24 am
    Hello There.. I dont know much about .htaccess I have a small issue, let me explain.. I have Joomla installed in the /Joomla directory.. eg: site .com/Joomla I want when a user comes to site .com, it automatically shows the content of site .com/Joomla and all the requests like site .com/index.php?com=xxx etc to site .com/Joomla/index.php?com=xxx means i want to remove the use of 'Joomla' string, without physically delete it Can anybody write that script for me, or guide me Thanks
  99. Tryna ~March 15, 2009 @ 1:51 pm
    your css has put a strike or del through everything, making it a little hard to read. Might want to fix that. Thanks!
  100. Ramesh ~March 2, 2009 @ 1:49 am
    hi all how to secure specified folder using in apache in htacces file..
  101. Mark ~February 15, 2009 @ 5:29 am
    These redirects work in my "httpd.conf" but not in my .htaccess file. My .htaccess is working because other directives work in there such as ErrorDocument. My setup is Apache 2.2, Tomcat 6.0, Windows. Any ideas?
  102. stu ~November 30, 2008 @ 1:38 pm

    nice tips, is missing a rule to block PHP injection attempts:

    RewriteCond %{QUERY_STRING} ^(.*)=http: [NC]
    RewriteRule ^(.*)$ - [F,L]
  103. santy ~November 8, 2008 @ 3:42 am
    hello everyone, I am new in php developing, i am do code for mod_rewrite for my site it is run well but problem is when i rewrite my URL page give right output but my css and images not appeared please sugest me for this prob thanks in advance… santy.
  104. KPLN! ~October 31, 2008 @ 8:42 am
    I think it can be great, adding more
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    .htaccess usage samples with file handlers. Please add some tutorials and .htaccess code samples about it.
  105. allQoo.com ~October 28, 2008 @ 1:29 am
    Thanks for the collection. It extends my understanding to the capability of a htaccess file : )
  106. J M ~October 20, 2008 @ 5:40 am
    Thanks, very useful .htaccess examples and well layed out.
  107. mosh ~October 15, 2008 @ 9:32 pm
    very nice .htaccess tutorial! now i can put hotlinking protection :) greetings!
  108. imel ~October 15, 2008 @ 1:57 am
    Hi, I just want to ask one question, for example: if I have website with URL address http://www.example.com/index.php?option=com_user But I just want to display URL like "http://www.example.com/". What should I do? Thanks in advance
  109. Rich LeClair ~October 14, 2008 @ 3:38 am
    Hey thanks for this tutorial - very awesome, but i still have a lot to learn about htaccess - mabe you can help me. i believe my request is simple. i want to take any request for http://www.example.com/img### where ### is an integer from 1 to 99999 and redirect the user to http://www.example.com/php/image_db/file.php?id=### where ### is said number. it seems easy enough? right? thanks for the help in advance!
  110. Nizzy ~September 18, 2008 @ 12:19 pm
    I like to generate a random directory name in the URL with .htaccess, is it possible?
    1. www.site.com
    2. .htaccess redirects to
    3. www.site.com/.sdf4p/
    so, I want to generate this ".sdf4p" string randomly for each request (directory names aren't generated in advanced, so I need to pick randomly. I just want to create that string randomly). but how? thanks for your help.
  111. Lokesh ~September 16, 2008 @ 11:02 am
    Hi, I have been stuck with this one for a pretty long time. I m zero when it comes to htacees. hence i need a little help. I have subdomain under my site mentioned above /iphone, working fine, but the link below to visit next pages does not work cuz the url is wrong. its supposed to be /iphone/page/pagenumber where as it shows up /page/pagenumber. my rewrite rule is
    RewriteRule ^iphone/page/([0-9999]+)/?$ /index.php?postpage=$1 [L,QSA]
    Can someone help me with this?
  112. PS Website Design ~August 27, 2008 @ 10:58 am
    Brilliant - just what I needed! Thanks for putting this htaccess rewrite guide together.
  113. Shomari Sharpe ~August 25, 2008 @ 2:33 am
    Hi i've tried your methods for activating url rewriting on my website but nothing happens. I test locally on my laptop running Kubuntu Linux 7.10 and nada. I desire to use rewrite for three specific php files.. Please i really need the help
  114. Rich Bowen ~August 11, 2008 @ 5:58 pm
    YES! YES! YES! rewrite .htaccess, hack htacess to hide index.php, static ip address,htaccess auto_prepend_file,htaccess rewritecond .php,php synchronize files,rewrite dynamic urls to flat
  115. david bowman ~July 25, 2008 @ 1:10 pm
    zomg, this is one of the most useful pages on the internets!
  116. Michael ~July 16, 2008 @ 3:43 pm
    @These are awesome..
    I wonder if you can help with one rule? I want to direct: domain/archive/some-text.php?123 to: domain/archive.php?123 I have tried multiple variations but can’t figure that out. Any ideas? I would sure appreciate it!!
    If you have tried the right variations you may not have Apache Rewrite enabled... But if you do... you could try something like this...
    Options +FollowSymLinks
    RewriteEngine On
    &nbsp;
    RewriteBase /
    &nbsp;
    RewriteCond %{HTTP_HOST} .
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule (.*) http://www.weathat.com/$1 [R=301,L]
    &nbsp;
    ## Activate the mod_rewrite Engine
    ## Support for LookBack + &#039;ForceType&#039;
    RewriteRule ^(index|shop)/(.*)$ index.php/$2 [L,NC]
    ## Support for Apache RewriteRule
    RewriteRule cat_([0-9]+)(\.[a-z]{3,4})?(\?.*)?$        index.php?_a=viewCat&amp;amp;catId=$1&amp;amp;$3 [L,NC]
    RewriteRule prod_([0-9]+)(\.[a-z]{3,4})?(\?.*)?$    index.php?_a=viewProd&amp;amp;productId=$1&amp;amp;%3 [L,NC]
    RewriteRule info_([0-9]+)(\.[a-z]{3,4})?(\?.*)?$    index.php?_a=viewDoc&amp;amp;docId=$1&amp;amp;$3 [L,NC]
    RewriteRule tell_([0-9]+)(\.[a-z]{3,4})?(\?.*)?$    index.php?_a=tellafriend&amp;amp;productId=$1&amp;amp;$3 [L,NC]
    &nbsp;
    RewriteRule _(saleItems)(\.[a-z]+)?(\?.*)?$   index.php?_a=viewCat&amp;amp;catId=$1&amp;amp;$3 [L,NC]
    --- I wouldn't recommend leaving the "?" in the display as this indicates a dynamic page and some search engines cannot index them. Good Luck.
  117. Stephen ~July 16, 2008 @ 12:23 am
    These are awesome.. I wonder if you can help with one rule? I want to direct: domain/archive/some-text.php?123 to: domain/archive.php?123 I have tried multiple variations but can't figure that out. Any ideas? I would sure appreciate it!!
  118. Marco ~July 9, 2008 @ 6:24 pm

    I use the following code on my site, however I would like the /support/ directory to be skipped, so the rewrites do not apply to it. I did try to place a .htaccess with RewriteEngine Off, in the support directory, however, that didn't do the trick.

    Any suggestions?

    Options +FollowSymlinks
    RewriteEngine on
    RewriteBase /
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
    &nbsp;
    # Rewrite current-style URLs of the form &#039;index.php?q=x&#039;.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.cgi?q=$1 [L,QSA]
  119. Tugacari ~July 7, 2008 @ 2:42 am
    Hi, I want to redirect all requests for flv files to another website dir. I have "www.site.com/flvideo/" and I want to redirect to "www.anotherdomain.com/flvideo/" What rewrite rule should I write in order to achieve this ? Thanks
  120. david ~July 5, 2008 @ 12:34 am
    wow , fantatist tips !! i ll try to do it for my website: I have only a question, is important for SEO the files end with .html ? like: web/page1.html or the simple can have an address like: web/page thanks! you can look my modrewrite with basic things
  121. Kpln ~April 8, 2008 @ 8:06 pm
    RewriteCond %{HTTP_HOST} !^domain.com [NC]
    RewriteCond %{HTTP_HOST} ^(www.)?([^.]+).domain.com [NC]
    RewriteRule ^$ /fake_subdomain.php?page=tag&amp;amp;tag=%2 [L]
    making sub domains can bee added :) good article thnx friend... Mod_rewrite favorite...
  122. article dude ~March 10, 2008 @ 9:17 pm
    Just a short note to thank you for this page, it has helped me countless times, I come here every time I need to modify my htaccess file so, many thanks for your help, I love the caching article too :) mark
  123. Ducky ~March 8, 2008 @ 12:16 pm
    Hey, I've been reading around your entries. Very helpful. :) I'm actually in a bind here, and maybe you could help? I'm noticing that .cur files that are missing are not recorded in my error log. I'm also unable to redirect or even just rewrite the cursor files that are missing to ones that exist. I'm using 403 404 500 and 301 back and forth to see if anything works, but so far, nothing. Help? :)
  124. Michael ~November 3, 2007 @ 6:51 pm
    I was working on some .htaccess file and moved all the NON-www to www. but in the process this also moved the subdomains like shop.weathat_com to www.weathat_com/shop/ Although this works and creates working pages, I would like to keep the non to www. redirect but also keep the subdomain non redirect. It isn't letting me do this so is there another way? Also I would like to make www.shop.weathat_com revert to shop.weathat_com My htaccess file looks like this.
    RewriteCond %{HTTP_HOST} .
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule (.*) http://www.weathat_com/$1 [R=301,L]
    RewriteEngine On
    RewriteBase /
    ++++ some other stuff for removing the dynamic URLs After all the searching on the Net I couldn't find the answer. And one more question? Is my Ranking Better for having the subdomain transfer to a directory folder? Thanks, Mike
  125. Douglas Karr ~October 20, 2007 @ 11:50 pm
    Great post! I've done a little work with .htaccess but I find the syntax a little confusing. Here's what I would like to do... I would like to create a 'mobile' theme for my blog and allow people to go to it simply by the subdomain. In other words, if the subdomain is www or no www, any direction to the themes would stay as they are: www.site.com/wp-content/themes/ However, if the subdomain is mobile: mobile.site.com Any references to the theme would be redirected to: www.site.com/wp-content/themes/mobile Is that possible? Thanks! Doug
  126. b.b.goyal ~October 20, 2007 @ 1:13 am
    i especially liked "some one is reading". how u implemented that?
  127. Chris [TK] ~October 19, 2007 @ 3:01 am
    wow... great tutorial :) thanks a lot :)
  128. Tim ~April 19, 2007 @ 5:44 pm
    Cool, we need this on TekTag.com. We've bookmarked it for ourselves, but I think the general community would like it.

Add Comment!

Leave a Reply

Your email address will not be published.


Google +

It's very simple - you read the protocol and write the code. -Bill Joy

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution 3.0 License, just credit with a link.
This site is not supported or endorsed by The Apache Software Foundation (ASF). All software and documentation produced by The ASF is licensed. "Apache" is a trademark of The ASF. NCSA HTTPd.
UNIX ® is a registered Trademark of The Open Group. POSIX ® is a registered Trademark of The IEEE.

Site Map | Contact Webmaster | Glossary | License and Disclaimer | Terms of Service |

↑ TOPMain