Search code examples
apache.htaccessmod-rewriteurl-rewritingfriendly-url

HTACCESS Rewrite Rule for Query String in PHP


I have my URL https://example.com/?hfgshdsds.

I need to rewrite a rule to makes that even If I removed the question mark , the link will works as same as before, so my url need to be https://example.com/hfgshdsds.

For the moment on my .htaccess file I have only the rule that open the php without extension .php .

RewriteEngine On
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L]

Thank you!


Solution

  • With your shown samples, please try following htaccess Rules file. Please make sure to clear your browser cache before testing your URLs.

    RewriteEngine On
    ##keep redirection Rules first then keep rest of rules.
    RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
    RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]
    
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule !.*\.php/?$ %{REQUEST_FILENAME}.php [QSA,L]
    
    ##Adding new rule here for non-existing pages here.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/?$ index.php?$1 [QSA,L]