Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache rewrite rule which works with or without a trailing slash

Tags:

I'm trying to redirect a series of static URLs, and I want it to work whether or not the trailing slash is present:

/foo/bar  --->  /tacos /foo/bar/  -->  /tacos 

I've tried the following, and all sorts of variations, but I always get a match only with the trailing slash present:

RewriteRule ^foo/bar?/$ http://url.com/tacos RewriteRule ^foo/bar(?/)$ http://url.com/tacos RewriteRule ^foo/bar*/$ http://url.com/tacos RewriteRule ^foo/bar(*/)$ http://url.com/tacos 

I feel like I'm missing something obvious. Help?

like image 827
Luke Dennis Avatar asked Oct 01 '10 21:10

Luke Dennis


People also ask

How do I remove trailing slash from URL?

We can remove a trailing slash from a URL LINK by using a combination of LEFT, RIGHT, and LEN functions.

How do Apache rewrite rules work?

mod_rewrite works through the rules one at a time, processing any rules that match the requested URL. If a rule rewrites the requested URL to a new URL, that new URL is then used from that point onward in the . htaccess file, and might be matched by another RewriteRule further down the file.

What is $1 in Apache rewrite rule?

The $1 is basically the captured contents of everything from the start and the end of the string. In other words, $1 = (. *) .

Is trailing slash required?

The short answer is that the trailing slash does not matter for your root domain or subdomain. Google sees the two as equivalent. But trailing slashes do matter for everything else because Google sees the two versions (one with a trailing slash and one without) as being different URLs.


1 Answers

Other than in EBNF or ABNF, a quantifier in regular expressions refers the preceding expression and not the following expression.

So:

RewriteRule ^foo/bar/?$ http://url.com/tacos 
like image 158
Gumbo Avatar answered Oct 03 '22 01:10

Gumbo