AleCat83
AleCat83

Reputation: 1493

rewrite rule: regular expression to remove variable from link

I've got urls like this one:

my-party/viewparty/243-party-in-berlin-2013.html

where the variable part of the url is:

243-party-in-berlin-2013.html

I neet to get a url like:

events/party-in-berlin-2013.html

how can I do it with the apache rewrite rule? I've managed to remove the "my-party/viewparty" but I can't remove the portion of variable link. Thank you very much

Alessandro

Upvotes: 1

Views: 334

Answers (1)

Decent Dabbler
Decent Dabbler

Reputation: 22783

The following will map any URI in the format:

my-party/viewparty/<digits>-<rest-of-file-name>.html

to

/events/<rest-of-file-name>.html

RewriteEngine On
RewriteCond %{REQUEST_URI} my-party/viewparty/\d+-([^\.]*\.html)$
RewriteRule .* /events/%1 [L]

The way it works, is that it captures (what's inside the parentheses) the last part (denoted by the dollar-sign) of the request uri, that ends with .html and is preceded by my-party/viewparty/\d+-, where \d+ denotes a string of digits, with a minimum length of one digit. It then appends this captured pattern (denoted by %1) to /events/ in the RewriteRule.

If you want to redirect (301 Moved Permanently) to the new URI, use:

RewriteEngine On
RewriteCond %{REQUEST_URI} my-party/viewparty/\d+-([^\.]*\.html)$
RewriteRule .* /events/%1 [R=301,L]

And, if the party-in-berlin-2013 part is not variable, then you could can simply replace the RewriteCond with this:

RewriteCond %{REQUEST_URI} my-party/viewparty/\d+-(party-in-berlin-2013\.html)$

Upvotes: 1

Related Questions