Search code examples
.htaccess

.htaccess and $_GET issue


My website use an OVH serveur Apache/2.4.38 (Debian10).

I have an issue with my .htaccess file, (I put it in /var/www/html, see here -> web tree)

I wanted to add some rewrite rules to have this URL :

https://example.fr/productPage1

instead of :

https://example.fr/productPage.php?id=1

here is what I put on my htaccess :

I tried this :

RewriteCond %{REQUEST_URI}  ^\/productPage\.php$
RewriteCond %{QUERY_STRING} ^id=([0-9]*)$
RewriteRule ^(.*)$ https://example.fr/productPage%1? [R=301,L]

But with a 404 error, because the _GET is no longer in the URL, how can I reach the _GET ?

(I have a lot of php functions using the CRUD method)

Thank you


Solution

  • Your question is: "... the _GET is no longer in the URL, how can I reach the _GET ?"

    The answer to that is: you can't, since there is not get argument in that URL. That actually is the whole point of this rewriting: not to have an ugly argument in the URL. Instead that argument is part of the path component of your desired URL. Which means that is where you need to get it from:

    RewriteEngine on
    RewriteRule ^/?productPage(\d+)$ /productPage.php?id=$1 [END]
    

    You can add an exernal redirection to this internal rewrite if you also want to redirect clients still using the old URL:

    RewriteEngine on
    RewriteCond %{QUERY_STRING} ^id=(\d+)$
    RewriteRule ^/?productPage\.php$ /productPage%1 [R=301]
    RewriteRule ^/?productPage(\d+)$ /productPage.php?id=$1 [END]
    

    You obviously need the rewriting module to be loaded and enabled for this to work.

    You should always prefer to implement such rules in the actual http server's host configuration, if possible . In situation where you do not have access to the host configuration you can also use a distributed configuration file (".htaccess"), but that comes with a number of disadvantages. And you need to enable that feature too (see the AllowOverride directive in the documentaiton).