user1275751
user1275751

Reputation: 3

Simple ReWriteRule expanded with an anchor

Hi from Central Australia, Thankyou for your help

I have a simple re-write like this

RewriteEngine on
RewriteRule Trades-Services-(.*) Trades-Services.php?cat=$1 [L,NC]

what this does is turns the URL like this

http://website.com/Trades-Services-Plumber

into this

http://website.com/Trades-Services.php?cat=Plumber

what I hope for is to further (or compliment) that rewrite rule so it will turn this

http://website.com/Trades-Services-Plumber-123

into this

http://website.com/Trades-Services.php?cat=Plumber&ad=123#123

e.g

http://website.com/Trades-Services-Civil-Celebrant-123
to
http://website.com/Trades-Services.php?cat=Civil-Celebrant&ad=123#123

Thankyou

Upvotes: 0

Views: 115

Answers (1)

Jon Lin
Jon Lin

Reputation: 143916

To do the bulk of the rewrite, you'd need to change your existing rules and add the extra one to handle the second case:

RewriteEngine on
RewriteRule ^Trades-Services-(.+)-([0-9]+)$ /Trades-Services.php?cat=$1&ad=$2 [L,NC]
RewriteRule ^Trades-Services-(.+)$ /Trades-Services.php?cat=$1 [L,NC]

This should cover 3 of your 4 requirements, except for the first:

Where it throws on an anchor as well (#123)

The URL fragment, the #123 bit, is handled by the browser and when urls have a #name in it, the #name fragment is never sent to the server. So there's no way the server knows about the fragment, it's something the browser sees and the browser seeks to the anchor in the document. Something you could do is redirect to get the anchor. The first rule would then look like this:

RewriteRule ^Trades-Services-(.+)-([0-9]+)$ /Trades-Services.php?cat=$1&ad=$2#$2 [L,NC,R]

However, when someone enters http://website.com/Trades-Services-Plumber-123 in their browser's address bar, that rule will REDIRECT the browser to http://website.com/Trades-Services.php?cat=Plumber&ad=123#123, thus what's in their browser's address bar changes to the php URI. This isn't the same behavior you have in your original rule (which redirects internally on the server-side, preserving what's in the browser's address bar). The other thing you can do is when you generate links like http://website.com/Trades-Services-Plumber-123, ensure that there's a fragment added to it: http://website.com/Trades-Services-Plumber-123#123.

Upvotes: 1

Related Questions