Mike Irish
Mike Irish

Reputation: 960

Adding a # symbol and redirecting to a url using htaccess

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]

Upvotes: 4

Views: 385

Answers (2)

anubhava
anubhava

Reputation: 785156

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.

Upvotes: 3

mister_cool_beans
mister_cool_beans

Reputation: 1533

something like this...

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

Upvotes: 1

Related Questions