Skip to content

General

IT Notes → URL Rewrite @ December 22, 2020

In URL rewriting the browser sends URL to server and server reconstructs it for the script. In redirection the new URL will be sent back to browser and the browser will have to request again. The search engines will update their databases. 301 redirection is permanent whereas 302 redirection is temporary.

URL rewriting allows you to completely separate the URL from the resource. Now one URL means one way to find a resource. For example, www.abc.com/aboutus may point to www.abc.com/page.php=1 and www.abc.com/help may point to www.abc.com/page.php=5.

URL rewriting module is

  • mod_rewrite for Apache and
  • ISAPI Rewrite for Windows IIS and requires payment of around 100$.
RewriteEngine On
RewriteBase /base
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING} !^id=0$
RewriteRule ^products/(.+)$ ^products.php?id=$1$ [L]

 

  • RewriteBase helps us to strip the base and perform regex with rest and prefix it back. It helps to ensure that .htaccess file is kept at root rather than various directories.
  • RewriteCond will match if the test string (URL portion) matches the pattern. In the example query stringmatched against not of (id=0). Only if this line is true will the next line be considered. %{HTTP_HOST}, %{HTTP_PORT}, %{QUERY_STRING}, %{REQUEST_FILENAME}, %{HTTP_COOKIE}, %{HTTP_USER_AGENT}, $1 (look ahead from rewriteRule), Special Patterns -d, -f, -s checks file directory, file or non-zero size file exists. Modifier flags are [OR] and [NC] (Case Insensitive).
  • RewriteRule will ensure that the passed URL potion is rewritten with $1 being the first match inside brackets. Here .(dot) means !=”” Modifier files [R=301] indicate 301 Permanent Redirection and [R=302] indicate 302 Permanent Redirection and [NC] indicates Case Insensitive and [L] indicates if rule matches Apache can stop now.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x