Martin Bean
Martin Bean

Reputation: 39409

mod_rewrite rule to match exact URL only

I'm having an issue with mod_rewrite where I want to match—and replace—a specific URL. The URL I want to rewrite is:

http://example.com/rss to http://example.com/rss.php

That means, if some one were to append anything after rss a 404 Not Found response be sent. Currently I'm using this mod_rewrite snippet:

Options -Indexes

RewriteEngine on
RewriteBase /

# pick up request for RSS feed
RewriteRule ^rss/?$ rss.php [L,NC]

# pass any other request through CMS
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+) index.php/$1

But this matches rss and rss with anything else added to the end. How can I re-write the above to acces only http://example.com/rss as the pattern for mod_rewrite to match against?

Upvotes: 0

Views: 7399

Answers (2)

anubhava
anubhava

Reputation: 785661

You are getting this error because /rss is being redirected twice in your rules by both RewriteRules. Have your rules like this:

Options +FollowSymlinks -MultiViews -Indexes
RewriteEngine On
RewriteBase /

# pick up request for RSS feed
RewriteRule ^rss/?$ /rss.php [L,NC]

# pass any other request through CMS
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (?!^rss\.php$)^(.*)$ /index.php/$1 [L,NC]

So with above rules it will redirect /rss OR rss/ URIs to /rss.php however /rss/foo will be redirected to /index.php since your 2nd rule is forwarding everything to /index.php

Upvotes: 2

jCoder
jCoder

Reputation: 2319

I was suprised to see that your rules just don't work, because in my first attempt I would have come to a very similar solution. But looking at the rewrite log revealed the real issue.

As discribed here the server prefers real files over directories. So internally rss/something becomes rss.php/something when applying the rewrite rules and things get weird.

So, one solution is to check if the Option MultiViews is enabled for the web directory either in .htaccess or in the vhost configuration. If so, remove it - which is what worked for me in this example.

If you need MultiViews, then I guess the only chance is to rename rss.php to rss-content.php and change the rule accordingly.

One additional note: you might want to add the following line after the # ... CMS block to prevent endless recursive calls.

RewriteRule ^index\.php/.* - [PT,L]

I hope this solves your rewrite problem.

Upvotes: 0

Related Questions