How to rewrite a URL using mod_rewrite?

by alvera_smith , in category: SEO , 2 years ago

How to rewrite a URL using mod_rewrite?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

2 answers

Member

by susan , 2 years ago

@alvera_smith 

To rewrite a URL using mod_rewrite in Apache HTTP Server, you can use the following syntax in your .htaccess file:

1
2
RewriteEngine on
RewriteRule ^old-url$ new-url [R=301,L]


This will redirect all requests to old-url to new-url with a 301 (permanent) redirect status code. The L flag is used to stop processing further rules.


You can also use regular expressions and pattern matching in the old-url to rewrite dynamic URLs.


For example, to redirect all requests for URLs starting with /blog/ to the same URL with /new-blog/ prepended:

1
2
RewriteEngine on
RewriteRule ^blog/(.*)$ /new-blog/$1 [R=301,L]


It's important to test your mod_rewrite rules thoroughly, as mistakes can result in a redirect loop or inaccessible pages.

by chasity.halvorson , 2 years ago

@alvera_smith 

mod_rewrite is a module for the Apache Web Server that allows you to rewrite URLs. To rewrite a URL using mod_rewrite, you need to add a rewrite rule to the .htaccess file in your website's root directory. The basic format of a rewrite rule is as follows:

1
2
RewriteEngine on
RewriteRule pattern target [flags]


  • RewriteEngine on enables the mod_rewrite module for the current directory.
  • pattern is a regular expression that matches the URL you want to rewrite.
  • target is the URL that the request should be redirected to.
  • flags are optional parameters that modify the behavior of the rewrite rule.


For example, to redirect example.com/old-page to example.com/new-page, you would add the following rule:

1
2
RewriteEngine on
RewriteRule ^old-page$ /new-page [R=301,L]


The [R=301,L] flag tells mod_rewrite to redirect the user to the new URL using a 301 permanent redirect, and to stop processing any more rewrite rules if this rule matches.