Biker John
Biker John

Reputation: 2711

Htaccess optional trailing slash when associating extensionless url with php

I use the following rule to associate extensionless url with php file.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.]+)/$ $1.php [NC,L]

I would like to change that to work no matter the ending trailing slash.

^([^\.]+)/$

Works with /example/

^([^\.]+)$

Works with /example

^([^\.]+)/?$

Tried with that one where slash is optional but not getting the desired result.

Upvotes: 1

Views: 106

Answers (1)

MrWhite
MrWhite

Reputation: 45914

^([^\.]+)/?$

This won't work as intended because regex is "greedy" by default, so the captured pattern consumes the trailing slash since it is optional at the end of the URL-path. In other words, a request for /foo/ ends up being rewritten to foo/.php, not foo.php as intended.

You need to make the captured group non-greedy, by using +? instead of +.

For example:

Options -MultiViews

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^.]+?)/?$ $1.php [L]

In addition...

  • The NC flag on the RewriteRule directive was superfluous.
  • No need to escape a literal dot in a character class.
  • You should ensure that MultiViews is disabled (to avoid potential conflicts in the future, if not already.)

Aside: However, by making both /foo/ and /foo resolve to the same page you are potentially creating a canonicalisation issue / duplicate content. You should decide which is the canonical and externally redirect one to the other.

Upvotes: 1

Related Questions