Search code examples
php.htaccessget

PHP file not able to access $_GET variable after .htaccess rewrite rule


I have a number of PHP pages with query strings in the URLs on my site. I'm trying to change the URLs for SEO, to do this I'm using an .htaccess file.

I'm new to .htaccess so this is fairly basic and I'm not sure if I'm doing this right or if there is a better way to do it.

My .htaccess file:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteCond %{REQUEST_URI} !/.css$
RewriteCond %{REQUEST_URI} !/.js$
RewriteCond %{REQUEST_URI} !/.png$
RewriteCond %{REQUEST_URI} !/.jpg$

RewriteRule ^category/([0-9a-zA-Z]+) category.php?id=$1
RewriteRule ^product/([0-9a-zA-Z]+) product.php?id=$1
RewriteRule ^page/([0-9a-zA-Z]+) page.php?page_id=$1

This allows me to access the page category.php?id=1 at category/1 the same for the other pages I have rewrite rules for. However my php script can no longer access the $_GET variable from the URL so it is rewriting correctly but now unable to show any of the content?


Solution

  • You will need to turn MultiViews option off and also do little bit refactoring of your rules.

    Options -MultiViews
    RewriteEngine on
    
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    
    RewriteRule ^category/([0-9a-zA-Z]+)/?$ category.php?id=$1 [L,NC,QSA]
    RewriteRule ^product/([0-9a-zA-Z]+)/?$ product.php?id=$1 [L,NC,QSA]
    RewriteRule ^page/([0-9a-zA-Z]+)/?$ page.php?page_id=$1 [L,NC,QSA]
    

    Option MultiViews (see http://httpd.apache.org/docs/2.4/content-negotiation.html) is used by Apache's content negotiation module that runs before mod_rewrite and makes Apache server match extensions of files. So if /file is the URL then Apache will serve /file.html.