简体   繁体   中英

RewriteRule to match all characters

So, I'm trying to write a htaccess file that will rewrite everything back to the root index file with a query added after it, so for example

example.com/cheese/ will route to example.com/index.php?cheese/

example.com/cheese will route to example.com/index.php?cheese

example.com/bob/fred will orute to example.com/index.php?bob/fred

going in as many layers as necessary, does anyone have an suggestions?

Currently trying this but it isn't working:

RewriteEngine on
RewriteRule ^(.*)/?$ index.php?$1

I know it isn't working because I am testing it with the following and the query output is not correct.

<?php
    $page = $_SERVER['QUERY_STRING'];
    echo $page;
?>

You can use this rule in your DOCUMENT_ROOT/.htaccess file:

RewriteEngine on

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

RewriteCond %{REQUEST_FILENAME} !-f will avoid looping and skip valid files like css, js images being rewritten to index.php .

Access the query string as:

$_SERVER["QUERY_STRING"]

At first, mod_rewrite must be enabled.

<IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteBase /
      RewriteRule /(.*) index.php?$1
</IfModule>

But if using $_SERVER['QUERY_STRING'] is a necessity I'd suggest using:

<IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteBase /
      RewriteRule . index.php
</IfModule>

and afterwards retrieve url from $_SERVER['REQUEST_URI'] , because your solution breaks every GET request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM