|
Home | Switchboard | Unix Administration | Red Hat | TCP/IP Networks | Neoliberalism | Toxic Managers |
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and bastardization of classic Unix |
News | mod rewrite | Recommended Books | Recommended Links | Flags |
RewriteBase directive | Perl Regular expressions | Tips | Humor | Etc |
|
mod rewrite uses Perl-compatible regular expressions.
|
A lot of the mod_rewrite "experts" and "gurus" floating around the net absolutely know their mod_rewrite, but what separates them from a beginner or novice is for the most part an understanding of what the URLS and Variables look like that are targeted by the regular expressions. Take this simple rewriterule that rewrites requests made without the www to www.
RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} !^www\.askapache\.com$ [NC] RewriteRule .+ http://www.askapache.com%{REQUEST_URI}Pretty simple right? WRONG. Most people could not figure that out..
By Garnet R. Chaney
Enabling server-side includes
- Server-side includes are macros within HTML expanded on the fly
- Dynamically
- Conditionally
- Usage:
AddType text/html .shtml
AddHandler server-parsed .shtml- See Apache's Handler Use and mod_include documentation for more information.
- ITS has documentation on Server Side Includes at Monash
Modifying the Environment
- Environment variables contain information used by server-side includes and CGI.
- For instance, an SSI statement: <--#echo SITE_WEBMASTER -->
- Setting, unsetting:
SetEnv SITE_WEBMASTER "Jack Sprat"
SetEnv SITE_WEBMASTER_URI mailto:[email protected]UnSetEnv REMOTE_ADDR
Adding new MIME types
- The type of file depends on the filename extension.
- Unrecognized file extensions are treated as text data, and corrupted on download.
- Examples:
AddType application/x-endnote-connection enz
AddType application/x-endnote-filter enf
AddType application/x-spss-savefile sav
Restricting documents
- .htaccess files provide a number of different ways to restrict documents:
- by accessor host address
- by browser type
- by accessor HTTP Basic credentials
- by phase of moon...
- Characterology campus-only access:
order deny,allow
deny from all
allow from 130.194 characterology.comAuthcate Restricted Documents
- Characterology Authcate credentials:
order deny,allow
deny from all
AuthType Basic
AuthName "Characterology Directory Service"
AuthLDAP on
AuthLDAPServer ldap://directory.characterology.com/
AuthLDAPBase "o=Characterology University, c=au"
require valid-user- It is possible to restrict who can access it even further
- Staff only
- Students only
- By Subject enrolment
- Specific individuals
- See the ITS documentation on MDS HTTP Authentication
- For restricting access so that non-Monash people can access it, consider AuthUserFile.
Protecting a single file
- Normally .htaccess applies to the entire directory
- With the <Files> directive you can restrict it to specific files:
<Files quiz.html>
order deny,allow
deny from all
AuthType Basic
AuthName "Characterology Student Authcate"
AuthLDAP on
AuthLDAPServer ldap://directory.characterology.com/
AuthLDAPBase "ou=Student, o=Characterology University, c=au"
require valid-user
satisfy any
</Files>- Another example - protecting the .htaccess file itself:
<Files .htaccess>
order deny,allow
deny from all
</Files>- <FilesMatch> does the same except using a regular expression wildcard.
Redirecting the client
- The server can be instructed to send a redirection back to the client whenever a particular URL is requested
- Several different types of redirection:
- permanent - the resource has moved permanently
- temp - it has temporarily moved elsewhere
- seeother - the resource has been replaced
- gone - it has been permanently removed
- Usage:
Redirect permanent /psych/subject/timetable http://www.characterology.com/psych/subject/ttableRedirect gone /psych/subject/1998
Redirect seeother /psych/subject/1999/ /psych/subject/2000/- The redirection applies to all documents under that URI path (eg., /psych/subject/1999/psy1011/books.html will be redirected to /psych/subject/2000/psy1011/books.html).
- See the Apache documentation on the Redirect statement for detailed information.
Rewriting the URL
- Unlike Redirect, the client is unaware of any server-side rewriting of the URL.
- Rewrite rules are applied repeatedly to the URL to change it into another URL.
- Example:
RewriteEngine on
RewriteBase /psychRewriteRule test/printenv(.*) cgi-bin/printenv$1
- The bracket-dot-star-bracket has special meaning: it is a regular expression
Aside: Regular Expressions
- Patterns ("wildcards") are matched against a string
- Normal alphanumeric characters are treated as normal
- Special characters:
- . (full stop) - match any character
- * (asterix) - match zero or more of the previous symbol
- + (plus) - match one or more of the previous symbol
- ? (question) - match zero or one of the previous symbol
- \? (backslash-something) - match special characters
- ^ (caret) - match the start of a string
- $ (dollar) - match the end of a string
- [set] - match any one of the symbols inside the square braces.
- (pattern) - grouping, remember what the pattern matched as a special variable
- Examples:
- a+ matches "a", "aaaa", "aaaaaaaaaaaa", but not "bbb"
- [ab]+ matches, "a", "b", or any length combination of the two
- \.s?html? matches ".htm", ".shtm", ".html" or ".shtml"
- (.+)/1999/(.+) matches "subject/1999/psy1011/", and also stores "subject" in $1 and "psy1011/" in $2.
- Regular expressions are very extensive.
- Documentation on silas: man regex
- Friedl (1997). Mastering Regular Expressions. O'Reilly.
More Rewrite voodoo
- Rewrites can be conditional, for example, rewrite only if the file could not be found:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)errata\.html?$ cgi-bin/errata/errata-html/$1RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule images/barcode/(.*).gif cgi-bin/barcode/mkgif?$1
- RewriteCond is very powerful. You can test on environment variable values:
RewriteCond %{HTTP_USER_AGENT} ^Mozilla.*
RewriteRule ^/$ /homepage.max.html [L]RewriteCond %{HTTP_USER_AGENT} ^Lynx.*
RewriteRule ^/$ /homepage.min.html [L]RewriteRule ^/$ /homepage.std.html [L]
- Full information on RewriteCond can be found within the Apache documentation on mod_rewrite
- The Apache URL Rewriting Guide is strongly recommended. Typical problems are presented along with their solution.
Want More Info About Apache Directives?
- Consult the Apache Directives Documentation.
Source: Liberal borrowing from http://www.its.monash.edu.au/web/slideshows/htaccess/all.htm
HostGator.com Support PortalWhat is mod_rewrite? Mod Rewrite allows you to change the URL that everyone sees when they visit your domain or a specific address. Just add the code to your .htaccess file (typically the one inside public_html).
Please remember we do not offer support to code this, nor do we promise to make your code work.
EXAMPLES
#Specify a default home page (index page)
DirectoryIndex home.html
#Allow only specified IPs to access your site
# Never use www in the domain
deny from all
allow from 64.95.219.140
allow from 210.23.45.67
# Replace 'example.com' with your domain name
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.(([a-z0-9_]+\.)?example\.com)$ [NC]
RewriteRule .? http://%1%{REQUEST_URI} [R=301,L]
# Always use www in the domain
# Set a default home directory, (this subfolder always loads)
# Replace 'example.com' with your domain name
RewriteEngine on
RewriteCond %{HTTP_HOST} ^([a-z.]+)?example\.com$ [NC]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .? http://www.%1example.com%{REQUEST_URI} [R=301,L]
# Replace 'folder' with your subfolder name
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^$ /folder/ [R=301,L]
</IfModule>
# Rename a directory and force visitors to the new name
# Always use https for secure connections
# Replace 'old' with your old folder name
# Replace 'new' with your new folder name
RewriteEngine on
RewriteRule ^/?old([a-z/.]*)$ /new$1 [R=301,L]
# Replace 'www.example.com' with your domain name
# (as it appears on your SSL certificate)
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
# Block traffic from multiple referrers
RewriteEngine on
Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} badsite\.com [NC,OR]
RewriteCond %{HTTP_REFERER} badforum\.com [NC,OR]
RewriteCond %{HTTP_REFERER} badsearchengine\.com[NC]
RewriteRule .* - [F]
Sunday, May 14, 2006
I have three kinds of mod_rewrite rules in my .htaccess file:
Through judicious application of these mod_rewrite rules, I have more or less complete control over the URLs people use to visit my site, and moreover, control over the way search engines deal with my old (and at times obsolete) content.
Once upon a time, I uploaded some mp3's to a super secret directory on my webserver so that I could download them at the office and enjoy some tunes on my horridly locked-down work machine. As you might guess, the super secret directory name was neither particularly super, nor spectacularly secret. MP3 search engines tracked down the directory within hours, and I realized my mistake after my bandwidth usage for the week skyrocketed.
I killed off the directory pretty quickly, but the damage was done. I was still getting tons of hits for those non-existent files, and the 'file not found' responses were making it pretty much impossible to get any useful information out of my error logs.
The right thing to do in this situation is to serve up a 410 ('Gone') HTTP error for any and all requests for files that were sitting around at some point in the past, but have since been removed. mod_rewrite makes this an absolute breeze:
RewriteCond %{REQUEST_URI} ^/mp3/ [NC] RewriteRule ^(.*) - [G,L]
In fact, I have a whole series of rules that return 410 errors. The relevant section of my .htaccess files looks like:
RewriteCond %{REQUEST_URI} ^/mint [NC,OR] RewriteCond %{REQUEST_URI} ^/mp3 [NC,OR] RewriteCond %{REQUEST_URI} ^/matchmaker [NC,OR] RewriteCond %{REQUEST_URI} ^/ars/? [NC] RewriteRule ^(.*) - [G,L]
The OR at the end of each RewriteCond chains them together in exactly the way you might imagine. If any of the conditions matches, then the rule triggers, and a 410 error code is returned. Brilliant!
Along with 410 error codes, you'll probably also find some use for 403 ('Forbidden') errors. For example, if you deploy content with CVS or SVN, then you've got files sitting around in your public document root that contain information you'd probably prefer not to share with everyone in the world (see Dan Benjamin's explanation for discussion of this very issue with Ruby on Rails' Capistrano). The files exist, so you shouldn't send a 404 ('Not Found') or a 410 ('Gone') error, but do you want to forbid access via the web. The following rules solve the problem:
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} ^(.*/)?CVS/ [NC,OR] RewriteCond %{REQUEST_URI} ^(.*/)?\.svn/ [NC] RewriteRule ^(.*) - [F,L]
The first line tests to see whether or not the requested CVS or .svn file actually exists before throwing a 403 ('Forbidden') error. It's a bit pedantic, but one ought not return a 'Forbidden' error for a file that's really 'Not Found'.
It's also worth noting here that the OR binds more tightly than the implicit AND in the first line. The rules therefore evaluate to something like "If the file exists AND (it's a CVS OR .svn file)", which makes sense for this application.
I've used a few domains over the lifetime of this blog, and search engines have links to files on all of them. Since I want all my URLs to refer to the same domain (to reduce confusion, and accumulate Page Rank correctly), I use mod_rewrite to map all requests to those other domains to my domain of choice. John Gruber's recent .htaccess article does a brilliant job explaining this sort of redirection, so I'll just note the syntax I use here (I like to explicitly note that the error code is 301 ('Moved Permanently') instead of using the full name, but that's simply personal preference; both work fine):
RewriteCond %{HTTP_HOST} ^(www\.)?reversal\.org$ [NC] RewriteRule ^(.*) http://mikewest.org/$1 [R=301,L]
Beyond differing domains, I've used a number of different URL schemas. Before I migrated to
TextPattern, each article on the site was accessible via a URL
that looked something like '/blog/id/<id number>'. I wasn't a huge fan of this URL schema, and I welcomed the
chance to flip to something that made more sense. The new URL schema looks like '/archive/<short title>', which
is friendlier both to end-users and search engines.
The problem, of course, is that the articles on the old site had been indexed by search engines, and linked by other bloggers. When I migrated to the new URL schema, I wanted to make sure that those old links would still go somewhere relevant.
There isn't much to say about this, really, as it's simply a manual mapping from URL #1 to URL #2 using a 301 ('Moved Permanently') error code:
RewriteCond %{REQUEST_URI} ^/blog/id/12 [NC] RewriteRule ^.*$ /archive/event-handlers-and-other-distractions? [R=301,L]
If you're planning a similar move, it would be best to determine which of your pages are actually linked regularly by
other sites, and generate the mod_rewrite rules that are most relevant to your circumstances. I examined my
'Not Found' error logs religiously for the first couple of days after moving to the new framework, and created mod_rewrite
rules for any errors that popped up more than once or twice.
This practice is actually a good ongoing maintenance idea. In his recent Django talk at Google, Jacob Kaplan-Moss mentioned that the Django team uses the 'Not Found' errors as a useful source of user suggestions. If people continually look for an '/archives/' URL, then maybe it's a good idea to make one, or write a mod_rewrite rule to direct that request to your '/past-posts/' page, etc. For example, I'm directing a few 'suggestions' to my bio:
RewriteCond %{REQUEST_URI} ^/resume.php [NC,OR] RewriteCond %{REQUEST_URI} ^/contact.php [NC,OR] RewriteCond %{REQUEST_URI} ^/contact/ [NC,OR] RewriteCond %{REQUEST_URI} ^/resume/ [NC,OR] RewriteCond %{REQUEST_URI} ^/bio.php [NC] RewriteRule ^(.*) http://mikewest.org/is/ [R=301,L]
This entry was published on Sunday, May 14, 2006. Articles published around the same time can be found in the archive.
Further reading: If you enjoyed this post, you might like to take a look at some of my other posts about 'HOWTO'. I've also made available a list of all the topics I've written about if you're interested in my (folkless) folksonomy.
Mod_Rewrite Tips and Tricks are lot of .htaccess rewrite examples that show specific uses for creating .htaccess rewrites to do all kinds of cool and profitable stuff for your site. 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 MooreNote: 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!
Some handy links to help you navigate this page:
- ≈ Htaccess rewrites TOC
- ≈ .htaccess rewrite examples should begin with:
- ≈ Require the www
- ≈ Loop Stopping Code
- ≈ Cache-Friendly File Names
- ≈ SEO friendly link for non-flash browsers
- ≈ Removing the Query_String
- ≈ Sending requests to a php script
- ≈ Setting the language variable based on Client
- ≈ Deny Access To Everyone Except PHP fopen
- ≈ Deny access to anything in a subfolder except php fopen
- ≈ Require no www
- ≈ Check for a key in QUERY_STRING
- ≈ Removes the QUERY_STRING from the URL
- ≈ Fix for infinite loops
- ≈ External Redirect .php files to .html files (SEO friendly)
- ≈ Internal Redirect .php files to .html files (SEO friendly)
- ≈ block access to files during certain hours of the day
- ≈ Rewrite underscores to hyphens for SEO URL
- ≈ Require the www without hardcoding
- ≈ Require no subdomain
- ≈ Require no subdomain
- ≈ Redirecting WordPress Feeds to Feedburner
- ≈ Only allow GET and PUT Request Methods
- ≈ Prevent Files image/file hotlinking and bandwidth stealing
- ≈ Stop browser prefetching
- ≈ Directives
- ≈ htaccess Guide Sections
Htaccess rewrites TOC
- .htaccess rewrite examples should begin with:
- Require the www
- Require no www
- Check for a key in QUERY_STRING
- Removes the QUERY_STRING from the URL
- Fix for infinite loops
- Redirect .php files to .html files (SEO friendly)
- Redirect .html files to actual .php files (SEO friendly)
- block access to files during certain hours of the day
- Rewrite underscores to hyphens for SEO URL
- Require the www without hardcoding
- Require no subdomain
- Require no subdomain
- Redirecting WordPress Feeds to Feedburner
- Only allow GET and PUT request methods
- Prevent Files image/file hotlinking and bandwidth stealing
- Stop browser prefetching
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
- RewriteBase
- RewriteCond
- RewriteEngine
- RewriteLock
- RewriteLog
- RewriteLogLevel
- RewriteMap
- RewriteOptions
- RewriteRule
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 tricks for Webmasters
- HTTP Header control with htaccess
- PHP on Apache tips and tricks
- SEO Redirects without mod_rewrite
- mod_rewrite examples, tips, and tricks
- HTTP Caching and Site Speedups
- Authentication on Apache
- htaccess Security Tricks and Tips
- SSL tips and examples
- Variable Fun (mod_env) Section
- .htaccess Security with MOD_SECURITY
- SetEnvIf and SetEnvIfNoCase Examples
" Search Engine Friendly Redirects | .htaccess Tutorial Index | " Speed up your site with Caching and cache-control
" Blocking Bad Bots and Scrapers with .htaccess
Undetectable Sniffing On Ethernet "My Picks
- Mod_Rewrite Tips and Tricks
- Crazy Advanced Mod_Rewrite
- THE Ultimate Htaccess
- THE Mod_Rewrite Cheatsheet
- Log Viewing in Console
- DNS: Round Robin Speed
- Fsockopen: PHP Socket-Level
- Rsync and SSH Transfer
Support Freedom or Die
Newest Posts
- Dealing with Mobile Visitors using Bad Browsers
- Magic in the Terminal: Screen, Bash, and SSH
- Advanced Windows Batch File Scripting
The love of liberty is the love of others; the love of power is the love of ourselves.
-- William Hazlitthtaccess Guide
- htaccess tricks for Webmasters
- HTTP Header control with htaccess
- PHP on Apache tips and tricks
- SEO Redirects without mod_rewrite
- mod_rewrite examples, tips, and tricks
- HTTP Caching and Site Speedups
- Authentication on Apache
- htaccess Security Tricks and Tips
- SSL tips and examples
- Variable Fun (mod_env) Section
- .htaccess Security with MOD_SECURITY
- SetEnvIf and SetEnvIfNoCase Examples
The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect. Tim Berners-Lee
Reader Comments
- 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
- ash ~
excellent post….thanks :)
- perochak ~
Hi,
I am looking for HTaccess code for Pagination.
I have the url as
http://site.com/article.php?do=read&page=5Any one can help??
Regards
Perochak- 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?
- 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]- 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]- 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.phpWhat I do to resolve this problem.
Thanks a lot for your response
- wyrmmage ~
The "Make a prefetching hint for Firefox." link goes nowhere, because the section is not present in the page.
- 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)
- Irfan Suleman ~
awesome, thanks
- 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
- 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- Roman ~
Leslie wrote:
I have a WordPress site and am using:
RedirectMatch 302 /download/example(.*) http://example.com/id=1234&profile=54321$1for 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.
- 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]- 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- 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.
- 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:
- Most important is getting read of the id "8″
- 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.
- 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
- pera webbhotell ~
Hi I need a RewriteCond that will take
http://site.se/site.sesite.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[]=.sehave been trying some days now….
- 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?
- 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_5if any access above URL it should be back to
www.site.com/pt/index.phpFYI: 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.
- 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.
- 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!
- Priya ~
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
- Php Resources ~
I found rewriting on my site with same using hyphen
- 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.
- 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-2086Any help much appreciate it.
Thanks,
Peter- 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.
- 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.htmlThis does a 301 (permanent redirect). 302 (temporary) is also possible.
- AskApache ~
http://www.microsoft.com/web/spotlight/urlrewriter/
- 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?
- 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- 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
- 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 :(
- 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.- 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_JavaScriptNEW URL (Required):
site.com/first_JavaScriptPlease guide me,
Regards,
Hussain- 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/etcit is simple enough to remove the index.php so the URL looks pretty, like:
www.domain.com/argument1/argument2/etcWhere 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/etcIs this possible?
- 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.
- 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.htmlto 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?
- 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]- Richard ~
Awesome job, this was the page that pulled all the pieces together for me.
Thanks!
Richard
- 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]- 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 ~
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).
- 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?
- 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
- 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
- EJ ~
Super htaccess article.
It was a good help to me.
Thanks.- 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 +FollowSymLinksat the beginning of their Prevent Hotlinks example. Is that correct/needed?
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.
- F. Fox ~
Great tips. All very usefull, and I needed them all!
Thanks!
- 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 :)
- 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]- 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- Leslie ~
I have a WordPress site and am using:
RedirectMatch 302 /download/example(.*) http://example.com/id=1234&profile=54321$1for 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?
- 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.
- 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
- Tryna ~
your css has put a strike or del through everything, making it a little hard to read. Might want to fix that.
Thanks!- Ramesh ~
hi all
how to secure specified folder using in apache in htacces file..
- 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?
- stu ~
nice tips, is missing a rule to block PHP injection attempts:
RewriteCond %{QUERY_STRING} ^(.*)=http: [NC] RewriteRule ^(.*)$ - [F,L]- 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.
- 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.- allQoo.com ~
Thanks for the collection. It extends my understanding to the capability of a htaccess file : )
- J M ~
Thanks, very useful .htaccess examples and well layed out.
- mosh ~
very nice .htaccess tutorial!
now i can put hotlinking protection :)greetings!
- 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- 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 99999and 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!
- Nizzy ~
I like to generate a random directory name in the URL with .htaccess, is it possible?
- www.site.com
- .htaccess redirects to
- 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.
- 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 isRewriteRule ^iphone/page/([0-9999]+)/?$ /index.php?postpage=$1 [L,QSA]Can someone help me with this?
- PS Website Design ~
Brilliant – just what I needed! Thanks for putting this htaccess rewrite guide together.
- 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
- 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
- david bowman ~
zomg, this is one of the most useful pages on the internets!
- 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.
- 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!!
- 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]- 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
- 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
- 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…- 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- 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? :)
- 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
- 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/mobileIs that possible?
Thanks!
Doug- b.b.goyal ~
i especially liked "some one is reading". how u implemented that?
- Chris [TK] ~
wow… great tutorial :)
thanks a lot :)
- Tim ~
Cool, we need this on TekTag.com. We've bookmarked it for ourselves, but I think the general community would like it.
Similar Reads
- htaccess HTTPS / SSL Tips, Tricks, and Hacks
- WordPress RewriteRules Viewer
- .htaccess mod_rewrite rewrite examples
- PHP htaccess tips and tricks
- htaccess Tricks for Webmasters
- Rewrite underscores to hyphens for SEO URL
- 301 Redirect with mod_rewrite or RedirectMatch
- Manipulating HTTP Headers with htaccess
- Redirect index.php to root
- SEO Redirects without mod_rewrite
- Smart HTTP and HTTPS .htaccess Rewrite
- Apache Authentication in htaccess
- Make phpBB SEO friendly with htaccess
Tags: 301 Redirect, 302 Redirect, 401, 403 Forbidden, Advanced, Apache, Apache Htaccess, Apache Modules, apache ssl, askapache, Bandwidth, Cache, Cache-Control, caching, cheatsheet, code snippets, CSS, Dig, errordocument, Examples, experiments, feed, FeedBurner, Firefox, Flash, GET, Hacking, hotlinking, Htaccess, htaccess guide, htaccess rewrite, htaccess tricks, htaccess tutorial, Htpasswd, HTTP Headers, httpd, httpd.conf, HTTPS SSL, Javascript, Login, Mod_Rewrite, Mod_Rewrite examples, Mod_Security, Nice, PDF, Perl, PHP, Port, Redirect, Redirecting URLS, Redirection, Request Method, Rewrite Tricks, rewritecond, rewriterule, Security, SEO, server, servers, SetEnvIf, SPEED, SSI, stat, SymLinks, trick, tutorial, WordPress,
Google matched content |
Society
Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers : Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism : The Iron Law of Oligarchy : Libertarian Philosophy
Quotes
War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda : SE quotes : Language Design and Programming Quotes : Random IT-related quotes : Somerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose Bierce : Bernard Shaw : Mark Twain Quotes
Bulletin:
Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 : Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law
History:
Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds : Larry Wall : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOS : Programming Languages History : PL/1 : Simula 67 : C : History of GCC development : Scripting Languages : Perl history : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history
Classic books:
The Peter Principle : Parkinson Law : 1984 : The Mythical Man-Month : How to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite
Most popular humor pages:
Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor
The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D
Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.
FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.
This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...
|
You can use PayPal to to buy a cup of coffee for authors of this site |
Disclaimer:
The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.
Last modified: July 28, 2019