4

I am attempting to rewrite the URL on my website using the .htaccess but have had no luck so far. I want to add a hash to the URL and redirect.

I want to get the last file in the URL and redirect it to the same URL but append a # symbol before the last file. The reason I want to do this is for my website, all the content is loaded dynamically without refreshing the page.

For example, www.example.com/foo would become www.example.com/#foo

or www.example.com/form/bar.php would become www.example.com/form/#bar.php

I don't mind if I need one entry for each page, I have tried many variations but nothing has worked so far.

RewriteRule ^(.*)foo(.*)$ $1#foo$2 [R=301,L]

RewriteRule ^(.*)/(.*)$ /$1#$2 [L,R=301,NE]
3
  • 2
    Try: RewriteRule ^foo/?$ /#$0 [L,NE,R=301,NC] Commented Feb 4, 2022 at 14:25
  • This kind of works, but it replaced everything with the #foo. So my local instance localhost/mywebsite/foo becomes localhost/#foo Commented Feb 4, 2022 at 14:40
  • Ok I will edit to make it clearer Commented Feb 4, 2022 at 14:52

2 Answers 2

3

Have it this way in your .htaccess:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^(.*/)([^/]+/?)$
RewriteRule ^ %1#%2 [L,NE,R=301]

A note about RewriteCond %{REQUEST_URI} ^(.*/)([^/]+/?)$:

We are using 2 capture groups in regex here:

  • (.*/): Match longest match before last / being represented as %1 later
  • ([^/]+/?): Match last component of URI being represented as %2 later

In target we use %1#%2 to place a # between 2 back references.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you briefly explain how this works, please?
Yes added it in question
1

something like this...

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/* /#$1 [NC]

3 Comments

Unfortunately, there's quiet a few things wrong here, such as... the pattern ^/* will never match, the $1 backreference is always empty, the # will be URL-encoded in the response (if this was a "redirect"), this is not a redirect (it needs to be an external redirect for JS to handle the response), etc.
Who is upvoting this?!
The ^/* matches and $1 is not always empty, I tested it before I posted it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.