Home > Back-end >  Url with showing 404 error code, how to fix?
Url with showing 404 error code, how to fix?

Time:10-08

Below are my .htaccess rules, the first rule is for example.com/search-words but showing 404 error code when you reach it like this example.com/search words while the second rule example.com/s/search-words is working in both.

RewriteRule ^([a-zA-Z0-9-z\-] )/?$ search_main.php?q=$1
RewriteRule ^s/(.*)?$ search_main.php?q=$1

How do I fix this?

CodePudding user response:

RewriteRule ^([a-zA-Z0-9-z\-] )/?$ search_main.php?q=$1

The RewriteRule pattern in the first rule does not permit spaces. Try the following instead:

RewriteRule ^([a-zA-Z0-9\s-] )/?$ search_main.php?q=$1 [L]

The RewriteRule pattern matches against the %-decoded URL-path. is a URL encoded space, so this regex must match a literal space character.

The \s shorthand character class denotes any white-space character.

You had an erroneous -z char sequence in the character class before the final hyphen. And there's no need to backslash-escape a literal hyphen when used at the start or end of the character class.

You should also include the L flag here.


UPDATE:

RewriteRule ^([a-zA-Z0-9:.–\s-] )/?$ search_maiin.php?q=$1 [L] Dot is redirecting home page to index.php @MrWhite

The dot is now likely causing a conflict with other rules (eg. a front-controller pattern) as it will now potentially match actual files, such as index.php.

You could make an exception for search phrases that end in .php, using a negative lookahead for example: ^(?!. \.php$)([a-zA-Z0-9:.–\s-] )/?$. In other words:

RewriteRule ^(?!. \.php$)([a-zA-Z0-9:.–\s-] )/?$ search_main.php?q=$1 [L]

OR, make sure the rule only applies to the initial request and not rewritten requests. For example:

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^([a-zA-Z0-9:.–\s-] )/?$ search_main.php?q=$1 [L]

NB: You had search_maiin.php (two is) in your revised rule (which I assume was a typo)?


UPDATE#2:

I'm requesting [index.php] directly.

I would not expect you to be requesting index.php directly. This will indeed create a conflict with the above rule, in that requests for index.php (or any .php file that is requested directly) will be routed to search_main.php.

Try the following instead, to specifically exclude requests for physical files (and directories):

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9:.–\s-] )/?$ search_main.php?q=$1 [L]
  • Related