2025.02.08 Redirects with #

There are cases where you want to redirect with a # (hash) in the URL.
However, the # gets URL-encoded, preventing the redirect from working correctly.

This configuration is intended to redirect /hoge/page1 to /hoge2#page1,
but it actually redirects to a URL like this:
https://hogehoge.com/hoge2%23page1

RewriteCond %{REQUEST_URI} ^/hoge/page1
RewriteRule ^ /hoge2#page1 [R=302,L]

Solution

Use an intermediate HTML file and redirect via JavaScript.

.htaccess

RewriteCond %{REQUEST_URI} ^/hoge/page1
RewriteRule ^ /hoge2_page1.html [R=302,L]

hoge2_page1.html


<script> window.location.href = "/hoge2#page1"; </script>