How to rewrite and redirect dynamic url to static url with htaccess

Rewrite and redirect are totally different thing. Mod_rewrite is a url rewriting means making another version of same url, it might be simple static url version of dynamic url, like example.com/?year=2070 to example.com/2070 . Redirect is forwarding from one url to another url. It’s all done in .htaccess file on root domain or root folder. That means you need to create .htaccess file with following code to rewrite and redirect.

Example 1> Here how you can rewrite and redirect example.com/?year=2070 to example.com/2070

RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} \?
RewriteCond %{QUERY_STRING} year=([0-9]+)
RewriteRule ^$ /%1? [R=301,L] RewriteRule ^([0-9]+)$ ?year=$1 [L]

You need to redirect first and then rewrite.

url rewrite

Example 2> Here how you can rewrite and redirect example.com/?year=2070&month=Baishakh to example.com/2070/Baishakh

RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} \?
RewriteCond %{QUERY_STRING} ^year=([0-9]+)&month=([a-zA-Z]+)$
RewriteRule (.*) http://example.com/%1/%2? [L,R=301] RewriteRule ^([0-9]+)/([a-zA-Z]+)$ /monthly/?year=$1&month=$2 [L]

Meaning and definition of character used in above code:

Char. Definition
\ Use before any of the following characters to escape or null the meaning or it. \* \. \$ \+ \[ \]
^ Start matching at this point
$ End point of the match
. Any character
[] Starts a class
| Starts alternative match this|that would mean match this or that
() starts a back reference point
? match 0 or 1 time Quantifier
+ match atleast 1 or more times Quantifier
* match 0 to infinite times Quantifier
{} match minimum to maximum Quantifier {0,3} match up to 3 times

 

Char. Definition
[R] Redirect you can add an =301 or =302 to change the type.
[F] Forces the url to be forbidden. 403 header
[G] Forces the url to be gone 401 header
[L] Last rule. (You should use this on all your rules that don’t link together)
[N] Next round. Rerun the rules again from the start
[C] Chains a rewrite rule together with the next rule.
[T] use T=MIME-type to force the file to be a mime type
[NS] Use if no sub request is requested
[NC] Makes the rule case INsensitive
[QSA] Query String Append use to add to an existing query string
[NE] Turns of normal escapes that are default in the rewriterule
[PT] Pass through to the handler (together with mod alias)
[S] Skip the next rule S=3 skips the next 3 rules
[E] E=var sets an enviromental variable that can be called by other rules

4 Comments

Leave a Reply