FREE THOUGHT · FREE SOFTWARE · FREE WORLD

Home  »  Htaccess  »  Htaccess Rewrites – Rewrite Tricks and Tips

by 150 comments


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!

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.

Tags

April 10th, 2011

Comments Welcome

  • Tim

    Cool, we need this on TekTag.com. We've bookmarked it for ourselves, but I think the general community would like it.

  • Chris [TK]

    wow... great tutorial :)

    thanks a lot :)

  • b.b.goyal

    i especially liked "some one is reading". how u implemented that?

  • http://www.douglaskarr.com Douglas Karr

    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

  • http://www.weathat.com/ Michael

    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

  • Ducky

    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? :)

  • article dude

    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

  • Kpln
    RewriteCond %{HTTP_HOST} !^domain.com [NC]
    RewriteCond %{HTTP_HOST} ^(www.)?([^.]+).domain.com [NC]
    RewriteRule ^$ /fake_subdomain.php?page=tag&tag=%2 [L]

    making sub domains can bee added :)
    good article thnx friend... Mod_rewrite favorite...

  • http://www.ssinfo.com.ar david

    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

  • Tugacari

    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

  • http://beijen.com/ Marco

    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]
     
    # Rewrite current-style URLs of the form 'index.php?q=x'.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.cgi?q=$1 [L,QSA]
  • Stephen

    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!!

  • Michael

    @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
     
    RewriteBase /
     
    RewriteCond %{HTTP_HOST} .
    RewriteCond %{HTTP_HOST} !^www.
    RewriteRule (.*) http://www.weathat.com/$1 [R=301,L]
     
    ## Activate the mod_rewrite Engine
    ## Support for LookBack + 'ForceType'
    RewriteRule ^(index|shop)/(.*)$ index.php/$2 [L,NC]
    ## Support for Apache RewriteRule
    RewriteRule cat_([0-9]+)(.[a-z]{3,4})?(?.*)?$        index.php?_a=viewCat&catId=$1&$3 [L,NC]
    RewriteRule prod_([0-9]+)(.[a-z]{3,4})?(?.*)?$    index.php?_a=viewProd&productId=$1&%3 [L,NC]
    RewriteRule info_([0-9]+)(.[a-z]{3,4})?(?.*)?$    index.php?_a=viewDoc&docId=$1&$3 [L,NC]
    RewriteRule tell_([0-9]+)(.[a-z]{3,4})?(?.*)?$    index.php?_a=tellafriend&productId=$1&$3 [L,NC]
     
    RewriteRule _(saleItems)(.[a-z]+)?(?.*)?$   index.php?_a=viewCat&catId=$1&$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.

  • david bowman

    zomg, this is one of the most useful pages on the internets!

  • http://httpd.apache.org/ Rich Bowen

    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

  • Shomari Sharpe

    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

  • http://www.pswebsitedesign.com PS Website Design

    Brilliant - just what I needed! Thanks for putting this htaccess rewrite guide together.

  • http://www.engadget.com/ Lokesh

    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?

  • Nizzy

    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.

  • Rich LeClair

    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!

  • imel

    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

  • mosh

    very nice .htaccess tutorial!
    now i can put hotlinking protection :)

    greetings!

  • J M

    Thanks, very useful .htaccess examples and well layed out.

  • allQoo.com

    Thanks for the collection. It extends my understanding to the capability of a htaccess file : )

  • KPLN!

    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.

  • santy

    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.

  • http://cyberdelix.net stu

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

    RewriteCond %{QUERY_STRING} ^(.*)=http: [NC]
    RewriteRule ^(.*)$ - [F,L]
  • Mark

    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?

  • Ramesh

    hi all

    how to secure specified folder using in apache in htacces file..

  • Tryna

    your css has put a strike or del through everything, making it a little hard to read. Might want to fix that.
    Thanks!

  • Rishi

    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

  • monokrome

    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.

  • Leslie

    I have a WordPress site and am using:

    RedirectMatch 302 /download/example(.*) http://example.com/id=1234&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?

  • Prasad

    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

  • Pollux

    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
     
    RewriteEngine On
    RewriteRule ^(.*).php$ /$1.html [R=301,L]
  • Chuck

    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 /
     
    # 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 :)

  • F. Fox

    Great tips. All very usefull, and I needed them all!

    Thanks!

  • jayanta

    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.

  • TrueFalse

    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!

  • EJ

    Super htaccess article.
    It was a good help to me.
    Thanks.

  • Andrew

    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&%{QUERY_STRING}

    It's dring me crazy :(

    Any help would be cool

  • mathguy

    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

  • Samson

    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?

  • pilot

    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).

  • pilot

    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]
  • pilot

    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]
  • Richard

    Awesome job, this was the page that pulled all the pieces together for me.

    Thanks!

    Richard

  • juan fernando

    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]
  • http://ionisis.com Vector Thorn

    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?

  • http://ionisis.com Vector Thorn

    Ah, i got it; i was using them for redirects, and now i see that by not actually redirecting you can accomplish this.

  • FMut

    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?

  • Hussain

    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

  • Q

    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.

  • art.mania

    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 :(

  • Adnan

    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

  • http://www.infonama.com Wasim

    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&cname=Website&mid=345&mname=My-Web"

    TO

    "www.mysite.com/Website/My-Web.html"

    would really appreciate any help from anyone :)
    Thanks

  • Jal Ulati

    @ 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?

  • http://www.askapache.com/ AskApache

    http://www.microsoft.com/web/spotlight/urlrewriter/

  • stu

    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.

  • argh

    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.

  • Peter Bearseley

    Hi Guys,

    Please advise me with the following redirect request?

    From
    http://www.site.com/lbr_ss?action=go_generic_link&category=SPORTS&level=CLASS&key=0037
    To
    http://sports.site.com/en-gb/Specials-2086

    Any help much appreciate it.

    Thanks,
    Peter

  • Phil

    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.

  • Php Resources

    I found rewriting on my site with same using hyphen

  • movers

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

  • sweta makode

    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&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.

  • Ali Honari

    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.

  • Abhi

    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?

  • http://winstart.se pera webbhotell

    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&tlds[]=.se

    have been trying some days now....

  • tonilony

    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

  • Alessio

    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.

  • revanth

    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.

  • Philippe

    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

  • Earneste

    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]
  • Roman

    Leslie wrote:

    I have a WordPress site and am using:

    RedirectMatch 302 /download/example(.*) http://example.com/id=1234&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.

  • Vikram

    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

  • Snehasis Mohapatra

    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

  • http://e-irfan.com Irfan Suleman

    awesome, thanks

  • http://briankurtz.com BrianMI

    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)

  • wyrmmage

    The "Make a prefetching hint for Firefox." link goes nowhere, because the section is not present in the page.

  • SALIM

    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

  • mejrel

    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&type=$2&price1=$3&price2=$4 [L]
  • Thomas

    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]
  • http://www.jbwebstudios.com Jerome Bailey

    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?

  • http://perochak.com/ perochak

    Hi,

    I am looking for HTaccess code for Pagination.

    I have the url as
    http://site.com/article.php?do=read&page=5

    Any one can help??

    Regards
    Perochak

  • http://www.tttt.com/ ash

    excellent post....thanks :)

  • rahat

    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

  • Severin

    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

  • http://www.zoomcreator.com michael

    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 ???

  • Julian

    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

  • Dale

    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

  • Bob

    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?

  • http://xuanluat.com Luat Nguyen

    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.

  • amsaraj

    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" ?

  • Tadi

    Hi,

    i had a url site.comBussinessxxxxxxxxxxxxx when someone hits the url site.comxxxxxxxxxxx it should redirect to site.comBussinessxxxxxxxxxxxxx even though i skip /Bussiness.

    what is the rewrite rule for that

  • amit

    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

  • lichti666

    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.

  • http://www.dotomize.com SuperZ

    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?

  • http://www.toiraq.com omar

    thinks

  • Prasanna

    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]
  • http://www.e-tigara.com Tig

    Yeah, great article. Have it bookmarked for about an year now, and still coming back to it for further notices ... awesome.

  • http://www.texas-explorer.com TexasExplorer

    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
  • # Ivo

    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
  • http://greendust.com/ Vijay Gupta

    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...?

  • http://positekreviews.com/reviews/ John

    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

  • http://www.high-on-it.co.za/ Markus

    Some worked great, but found one for my needs, had to remove the html completely and replace with an "/" wordpress style

  • http://www.facebook.com/ciges Ciges

    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 :-)

  • http://www.webperfection.net kuko

    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

  • raghu

    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.

  • Webmonkey

    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!

  • http://www.askinterview.com sumit

    hello,
    no man its not working is that any other idea to let me out of this.........

  • http://www.nuttytimes.com/ Angelon

    wow.. thank u soo much.. this information really helped me

  • http://www.idemdesign.net Danilo

    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.

  • http://www.solvonix.com Sumit Kumar

    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

  • http://www.ioasw.com iconus

    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!

  • Thomas

    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 ?

  • http://interviewquestionsanswers.org/ Ali Muaviah

    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.

    • http://www.askapache.com/ AskApache

      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.

  • http://www.colinthompson.co.uk Colin

    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

  • ramesh

    thanks Man!!! perfect tutorial

  • Sandra

    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 /.

  • http://lostmon.blogspot.com Lostmon

    Thnx for this MASTER Class !!
    it has helped me so many times !!!!!

  • John

    Thanks. Looking all day for something like your cache friendly file names. great solution, just what I needed.

  • Kellie

    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?

  • Thomas [TA]

    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!

  • http://socialblogsitewebdesign.com sergio

    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)

  • http://www.my-favorite-hikes.com ken shoufer

    Good information for web site security. I will try to put it into practice soon. Thanks very much.

  • http://www.theperfectarts.com Gunjan

    The "Rewrite underscores to hyphens for SEO URL" is really good one.

  • Michael

    --> Cache-Friendly File Names
    good idea.
    it replaces /zap/j/anything.js?anynumber e.g. /zap/j/anything.js?1328132908871 which is very often to be seen

  • Gabriel Tavares

    Hi guys, i have the following code on my htaccess, but i want to redirect the blocked UA to a specific web page. How can i do this?
    code:

    (...)
    SetEnvIfNoCase ^User-Agent$ .*web(zip|emaile|enhancer|fetch|go.?is|auto|bandit|clip|copier|master|reaper|sauger|site.?quester|whack) HTTP_SAFE_BADBOT
    SetEnvIfNoCase ^User-Agent$ .*Web(site.?(extractor|quester)|collage|snake|ster|strip|suck|vac|walk|whacker|zip) HTTP_SAFE_BADBOT
    SetEnvIfNoCase ^User-Agent$ .*(craftbot|download|extract|stripper|sucker|ninja|clshttp|webspider|leacher|collector|grabber|webpictures) HTTP_SAFE_BADBOT
    SetEnvIfNoCase ^User-Agent$ .*(libwww-perl|aesop_com_spiderman) HTTP_SAFE_BADBOT
    Deny from env=HTTP_SAFE_BADBOT

    Thanks

  • NameSilvio

    Greate tutorial, very complete!

  • http://sagalink.net/ Sua may tinh

    Removing the Query_String ^ does not work, have any solution

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

    Awsome ... I have been looking at alot of .htacess pages for two years or so but this is the best. I will Tweet this site. :)

  • http://vaporcreations.com Joshua VaporCreations.com

    AskApache has been a formidable resource with my knowledge and use of the .htaccess file for a long time now. I have gained many valuable variables from AskApache which I use on a daily bases when it comes to restricting and redirecting search bots for SEO and page ranking reason.

  • http://www.wordpress-how-to-videos.com Nicole

    Hi there, You have done a great job. I will definitely digg it and personally recommend to my friends.
    I'm confident they'll be benefited from this site.

  • http://wellhatched.multiply.com/journal heike

    It's a shame you don't have a donate button! I'd definitely donate to this brilliant blog! I suppose for now i'll settle for bookmarking and adding your RSS feed to my Google account.
    I look forward to fresh updates and will talk about this website with my Facebook
    group. Talk soon!

    • http://www.askapache.com/ AskApache

      @heikie

      Thanks I just added a donate to the sidebar.

  • http://URL stevefal

    I have a new site implementation site that uses URL parameters for only Search - nowhere else. But since the old site used URL parameters off the root (site.com/?pid=1) those URLs are floating around on the web.

    Can you suggest a way to redirect site.com/?pid=1 to site.com, without stripping URL parameters in other cases, such as site.com/search.html?search=foo?

  • Corné Vermeulen

    I need a modrewrite that will cancel all modrewrite rules if it is a certain url request, how can I do it?

  • http://www.podomatic.com/profile/grip73earth Flanders

    Your style is really unique compared to other people I've read stuff from. Many thanks for posting when you've got the opportunity.. bookmarked!

  • http://nuyganut.com/webboard/index.php?action=profile;u=247410 Ullas Soman

    Thanks so much for the post this is exactly what I
    needed today!!!

  • Mitch

    Great explanation, just what i needed. Been driving myself mad trying to cover non-www redirects on that allow for subdomains. Thanks again!

  • Mitch

    Great explanation, just what i needed. Been driving myself mad trying to cover non-www redirects on that allow for subdomains. Thanks again!

  • S Adam

    Thanks for great post .. I have been through this trying to find a way to rewrite this >> .feed?type=rss <> .feed?type=rss&format=feed << So i need to add the &format=feed part .. I can not find a way to do it any ideas. Thanks in advance

  • Ezra

    What does this mean, when only this code? : RewriteEngine On

    • Ezra

      nevermind .. rewrite ;) .. Excellent subject

  • Pingback: Apache + Godaddy + Cloudflare + CNAME + .htaccess RewriteRules – Creating a subdomain (the hard way heh) | The PHP Coder's Judy Chop

  • Pingback: .htaccess | CourseVector Staff

  • http://www.hippressurecooking.com/ Laura – Hip Pressure Cooking

    Would love to see an example of how to re-write any URL that matches a patter, for my needs it would be "starts with xyz" and redirect it to one page.

    For example I moved my blog from blogger to wordpress and I'm getting lots of access errors for old file locations that look like this...
    search?updated-max=bla bla bla bla bla

    I want to redirect them to the new "blog" on the website. Can I just add a * at the end like...

    RewriteCond %{QUERY_STRING} ^search?updated-max=*
    RewriteRule /previous-articles/ [R=301,L]

    Thanks,

    L

  • Kubodo Architecture

    can you help me.
    i have .htaccess like
    RewriteRule ^index.html$ /index.php [QSA]
    RewriteRule ^pdf/.* /a-single.php [QSA]
    RewriteRule ^ebook/.* /a-single-e.php [QSA]

    output:
    /pdf/post-title-id.pdf
    /ebook/post-title-id.pdf
    and i want to change those to
    post-title-id.pdf
    post-title-id.pdf

    help me please

  • Ashish Bohara

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

Popular Articles
My Online Tools

Related Articles
Newest Posts
Twitter



Hacking and Hackers

The use of "hacker" to mean "security breaker" is a confusion on the part of the mass media. We hackers refuse to recognize that meaning, and continue using the word to mean someone who loves to program, someone who enjoys playful cleverness, or the combination of the two. See my article, On Hacking.
-- Richard M. Stallman






[hide]

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.

| Google+ | askapache

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

↑ TOPMain