Home > Mobile >  Remove ?q= from url with htaccess
Remove ?q= from url with htaccess

Time:10-27

I want this:

https://example.com/something

From this:

https://example.com/?q=something

I found many similar questions stackoverflow, but none of them worked for me, so please help me.

For example i tried this:

RewriteEngine On
RewriteRule ^(.*) index\.php?q=$1

with this php code:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Document</title>
  </head>
  <body>
    <?php echo $_GET['q'] ?>
  </body>
</html>

but it's always shows "index.php"

CodePudding user response:

RewriteRule ^(.*) index\.php?q=$1

...but it's always shows "index.php"

That's because the rather generic pattern ^(.*) also matches index.php and ends up rewriting the request to index.php?q=index.php on the second pass of the rewrite engine (when used in a directory context, like .htaccess).

If your URL's (like /something) don't contain dots then you could simply exclude dots from the regex, so it won't match index.php. Excluding dots also means it should avoid matching any static resources (that usually map directly to files that end in a file extension, which are naturally delimited by a dot, eg. image.jpg, styles.css, etc.).

For example, try the following instead:

RewriteRule ^([^.]*)$ index.php?q=$1 [L]

There's no need to backslash-escape the literal dot in the substitution string (2nd argument) since this is a "regular" string, not a regex, and the dot carries no special meaning here.

  • Related