RewriteEngine – 3 steps basics

This article was completely stolen from: http://tomclegg.net/rewriterule (Thank you Tome. It helped me.) The reason i did it, is that i was spending long time looking for right this compilation of examples. I like to distribute this simple but powerful basic code.

If http://example.com/foo/bar does not exist, redirect to http://other.example.com/foo/bar. (Put this in an .htaccess file in your top-level web directory.)

.htaccess in root of example.com

  1.  
  2. RewriteEngine On
  3. RewriteCond %{REQUEST_FILENAME} !-f
  4. RewriteCond %{REQUEST_FILENAME} !-d
  5. RewriteRule ^(.*)$ http://other.example.com/$1 [R]
  6.  

Handle all requests for top-level .html files and files with no extensions (http://example.com/foo, http://example.com/foo.html) with a single PHP program /foo/show.php. Also, ignore trailing characters in set { : ; , . } so URLs like “http://example.com/foo.” can be copied-n-pasted from plain text sentences by inattentive users.

.htaccess in root of example.com

  1.  
  2. RewriteRule ^/?([^/]*\.html?|[^\./]*)[:;,\.]*$ /foo/show.php [L,NS]
  3.  

Examples:

http://tomclegg.net/rewriterule
http://tomclegg.net/rewriterule.html;

Redirect GET requests for http://example.com/foo/bar to http://example.com/bar (and /foo/bar.html to /bar.html). Handle POST requests with PHP program rather than attempting to redirect a POST (which is unlikely to work well).

.htaccess in foo folder in example.com’s document root

  1.  
  2. RewriteEngine On
  3. RewriteCond %{REQUEST_METHOD} GET
  4. RewriteRule ^/?([^/]*\.html?|[^\./]*)[:;,\.]*$ /$1 [R,L,NS]
  5. RewriteCond %{REQUEST_METHOD} POST
  6. RewriteRule ^/?([^/]*\.html?|[^\./]*)[:;,\.]*$ /foo/show.php [L,NS]
  7.  

Examples:

http://tomclegg.net/w/rewriterule
http://tomclegg.net/w/rewriterule.html;

Comments are closed.