htaccess returning 500 error when needs to be 404

2019-07-09 07:46发布

问题:

How can I make it so that my htaccess rules return a 404 when invalid urls are entered into the address bar.

The two rules that are causing this

RewriteRule ^submit/([a-z]+)/([0-9]+)$ /submit?c=$1&i=$2 [L]

RewriteRule ^test/([a-z]+)/([0-9]+)/([0-9]+)$ /test?c=$1&i=$2&q=$3 [L]

Both the rules work fine when a correct url is entered but say for example one of the last parameters is not a number, it returns a 500 error.

How can I make it so that if these rules are not matched then it'll return a 404.

To further clarify take the following url test/cooking/9/1 is valid. So is submit/cooking/9.

It returns 500 with urls that dont match the rewrite such as these, 'test/cooking/9/1/1,submit/0/0/0`, I would like it to return a 404 if the rules outlined above are NOT matched.

FULL .htaccess FILE

# Turn on rewriting engine
RewriteEngine On

# Internally rewrite submit parameters
RewriteRule ^submit/([a-z]+)/([0-9]+)$ /submit?c=$1&i=$2 [L]

# Internally rewrite test parameters
RewriteRule ^test/([a-z]+)/([0-9]+)/([0-9]+)$ /test?c=$1&i=$2&q=$3 [L]

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

# Externally redirect .php
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php
RewriteRule ^/?(.*)\.php$ /$1 [L,R=301]

# Add default charset for files
AddDefaultCharset UTF-8

# G-zip deflate compression
<FilesMatch "\\.(js|css|html|htm|php|xml)$">
     SetOutputFilter DEFLATE
</FilesMatch>

回答1:

This is happening because apache is reading the URI as part of the PATH INFO, and parts of test or submit is matching the -f check eventhough the rest of the path doesn't. Try changing the -f check to:

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}\.php -f

instead of:

RewriteCond %{REQUEST_FILENAME}\.php -f