Blackbam
Blackbam

Reputation: 19376

Apache .htaccess: Redirect to an URL containing a hashtag

The URLs

https://example.com/moved/

https://www.example.com/moved/

should be redirected to the URL

https://my.example.com/#views/settings.php?id=2

via .htaccess.

This is what I have tried:

RewriteCond %{HTTP_HOST} ^example.com
RewriteCond %{REQUEST_URI} moved$
RewriteRule (.*)$ https://my.example.com/#views/settings.php?id=2 [R=301,L]

However it seems not to work. I guess the reason is the #hashtag within the URL where I want to redirect to (it marks a comment within .htaccess).

How to redirect this correctly?

Upvotes: 4

Views: 1603

Answers (1)

anubhava
anubhava

Reputation: 785196

Change your rule to this:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(?:www\.)?example\.com$ [NC]
RewriteRule ^moved/?$ https://my.example.com/#views/settings.php?id=2 [R=301,L,NE,NC]
  • ^(?:www\.)?example\.com$ will match www.example.com and example.com
  • Flag NE is used for no escaping of # in redirected URL
  • Pattern moved/?$ matches /moved/ and /moved, thus making trailing slash optional.

Make sure to clear your browser cache or use a new browser for testing.

Upvotes: 4

Related Questions