Search code examples
php.htaccess

A htaccess redirects incorrectly


This is my htaccess:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]

RewriteCond %{THE_REQUEST} \s/category\.php\?catid=(\S+)\s [NC]
RewriteRule ^ /news/categories/%1? [R=301,L]

RewriteCond %{THE_REQUEST} \s/article\.php\?title=(\S+)\s [NC]
RewriteRule ^ /news/%1? [R=301,L]

RewriteCond %{REQUEST_URI} !/(exception\.php|admin) [NC]
RewriteCond %{THE_REQUEST} \s/([^.]*)\.php/?\s [NC]
RewriteRule ^ /%1? [R=301,L]

RewriteRule ^news/categories/([^/]*)$ category.php?catid=$1 [NC,QSA,L]

RewriteRule ^news/([^/]*)$ artice.php?title=$1 [NC,QSA,L]

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

My problem is that when a user open this URL: XYZ.com/news/categories – it redirects to XYZ.com/404.

I want to avoid this and show him cats.php which is in my base directory. But of course, the URL should continue to remain as XYZ.com/news/categories, only the cats.php file should be loaded for it.

Thank you for your help!


Solution

  • You need an additional rule to handle /news/categories which would be like this:

    RewriteRule ^news/categories/?$ cat.php [NC,L]
    

    Your full .htaccess can be like this:

    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [R=301,L]
    
    RewriteCond %{THE_REQUEST} \s/category\.php\?catid=(\S+)\s [NC]
    RewriteRule ^ /news/categories/%1? [R=301,L]
    
    RewriteCond %{THE_REQUEST} \s/article\.php\?title=(\S+)\s [NC]
    RewriteRule ^ /news/%1? [R=301,L]
    
    RewriteCond %{REQUEST_URI} !/(exception\.php|admin) [NC]
    RewriteCond %{THE_REQUEST} \s/([^.]*)\.php/?\s [NC]
    RewriteRule ^ /%1? [R=301,L]
    
    RewriteRule ^news/categories/?$ cat.php [NC,L]
    
    RewriteRule ^news/categories/([^/]+)/?$ category.php?catid=$1 [NC,QSA,L]
    
    RewriteRule ^news/([^/]+)/?$ artice.php?title=$1 [NC,QSA,L]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^(.+?)/?$ $1.php [L]