简体   繁体   中英

Internal Server Error when rewriting URL to remove extension .htaccess

I'm using .htaccess to remove .php extension on my website. But in some cases it says "Internal Server Error".

Here's my .htaccess code:

AddHandler x-httpd-php5-6 .php

Options +FollowSymLinks
RewriteEngine on
RewriteRule productos/(.+)/? /prueba/listado-productos.php?category=$1
RewriteRule productos/(.+)/(.+)/? /prueba/listado-productos.php?category=$1&subCategory=$2
RewriteRule productos/(.+)/(.+)/(.+)/? /prueba/listado-productos.php?category=$1&subCategory=$2&product=$3
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php

The code to rewrite the URLs to remove .php extension are the last three lines.

Suppose I have a folder called directory and a file called about.php in the root folder:

example.com -----> works
example.com/directory ----> works
example.com/directory/ ----> works
example.com/about ----> works
example.com/about/ ----> internal server error

How can I fix this? I've tried everything!

When you debug this, eg set LogLevel debug rewrite:trace2 , you will see that the request /about/ is rewritten to /about/.php , and again to /about/.php.php , and again to /about/.php.php.php , and so on, until it eventually fails with

AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error.

You can prevent this with an additional rule, which considers the trailing slash. This rule is more or less the same you already have

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

The only difference is the trailing slash in the rule's pattern. This will rewrite the request /about/ to /about.php instead of /about/.php , and therefore find the proper script instead of looping.


If you want to minimize the number of rules, eg only one instead of these two rules, you may also try this slightly modified pattern

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

This pattern matches both /about and /about/ , and this way you have it in one go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM