Search code examples
phphtmlapache.htaccessmod-rewrite

why url with slash gives 404 error on website?


I want URL with slash / at the end.

On my website if I the enter URL with slash / at the end it is giving 404 error.

I modified .htaccess file with the below code. Still not working.

AcceptPathInfo Off
RewriteBase /
RewriteCond %{THE_REQUEST} //
RewriteRule ^ - [L,R=404]
RewriteEngine On
RewriteRule \.php/.+$ [L,NC,R=404]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^blog/([A-Za-z0-9-]+)/?$ inner.php?slug=$1 [NC,L]
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Solution

  • RewriteRule ^([^\.]+)$ $1.php [NC,L]
    

    This (last) rule unconditionally rewrites any remaining URLs (that do not contain a dot) to append a .php extension. However, if you include a trailing slash on the requested URL, eg. /foo/, then it will rewrite the request to /foo/.php (instead of /foo.php) which will result in a 404 and is most certainly the cause of your problem.

    You need to exclude the (mandatory) trailing slash from the captured subpattern. For example:

    RewriteRule ^([^.]+)/$ $1.php [L]
    

    (Aside: No need to backslash-escape literal dots when used inside a regex character class and the NC flag is superfluous here, since the RewriteRule pattern does not differentiate case anyway.)

    However, you should really be testing that the target .php file exists before rewriting the request, otherwise you are going to get 404's triggered by /requested-url.php, rather than /requested-url (the URL that was actually requested). In other words:

    RewriteCond %{DOCUMENT_ROOT}/$1.php -f
    RewriteRule ^([^.]+)/$ $1.php [L]