Home > Enterprise >  Regex for htaccess redirect (with exceptions!)
Regex for htaccess redirect (with exceptions!)

Time:10-11

I am looking forward to redirect hundreds of URL belonging to the path https://example.com/fragen/, for example:

https://www.example.com/fragen/amazonerstattungen/
https://www.example.com/fragen/sonderbetriebsvermoegen/
https://www.example.com/fragen/troedel/

to a single URL like https://www.example.com/wiki/

Could you please suggest me the correct regex expression to be included in the .htaccess to attain this goal?

Besides, a few URLs belonging to the /fragen/ path should be redirected separately. I suppose that these redirects should precede the regex expression in the code block in object. Is that correct?

CodePudding user response:

Using mod_rewrite, near the top of your root .htaccess:

RewriteEngine On

# Specific Redirects
RewriteRule ^fragen/specific-url$ /somewhere-else [R=302,L]
RewriteRule ^fragen/another-url$ /another-url [R=302,L]

# Redirect everything else in "/fragen/" to "/wiki/"
RedirectRule ^fragen/ /wiki/ [R=302,L]

The regex ^fragen/ matches any URL-path that starts fragen/. Note that the URL-path matched by the RewriteRule directive does not start with a slash.

And yes, as you suggest, specific redirects need to precede the generalised redirect.

Note that these are 302 (temporary) redirects. Always test first with 302s to avoid potential caching issues. Only change to a 301 (permanent) redirect - if that is the intention - once you have confirmed it works as intended.

Aside: This might not have the SEO benefit you are hoping. A many-to-one redirect like this is often seen as a soft-404 by search engines. And users often bounce. It is often preferable to implement a custom 404 response and offer an explanation to the user where the page has gone.

  • Related