How to use regex in htaccess to redirect certain urls?

by darrion.kuhn , in category: Third Party Scripts , a month ago

How to use regex in htaccess to redirect certain urls?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , a month ago

@darrion.kuhn 

To use regex in .htaccess to redirect certain URLs, you can use the RewriteRule directive with the following syntax:

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


In this example, "^old-url$" is a regular expression that matches the specific old URL you want to redirect. "/new-url" is the new URL you want to redirect to. The "[R=301,L]" flags indicate that the redirection should be a permanent (301) redirect and that it should be the last rule applied.


You can also use more complex regular expressions with capture groups to redirect more dynamic URLs. For example:

1
2
RewriteEngine On
RewriteRule ^category/([a-zA-Z0-9-]+)$ /products?category=$1 [R=301,L]


In this example, "^category/([a-zA-Z0-9-]+)$" matches URLs like "/category/some-category" and captures the category name as $1. The redirect sends the user to "/products?category=some-category".


Make sure to test your regex and redirects thoroughly to ensure they are working as expected. Also, keep in mind that incorrect use of regex in .htaccess can lead to unexpected behavior on your website.