.htaccess URL rewrite to match symbols, letters an

2019-09-06 21:15发布

问题:

I am trying to rewrite this URL:

localhost/classifieds/index.php?page=activate&extra=$2y$10$LsV9m8JgEz2zMaJYRNqocuOzaqR8oHmn3tBIjIQv.TI4JWd3rWVrC

to:

localhost/classifieds/activate/$2y$10$LsV9m8JgEz2zMaJYRNqocuOzaqR8oHmn3tBIjIQv.TI4JWd3rWVrC

Now, the first part is successful, if I enter:

localhost/classifieds/activate

it gives me:

localhost/classifieds/index.php?page=activate

Hereby, loading the right controller.

My major problem is that I want the rule to also rewrite the second part of the URL.

I tried different regex combinations, but all to no avail.

回答1:

In order for classifieds/activate/whatever to silently hit the index.php?page=activate&extra=whatever, you need something like this:

Options +FollowSymLinks

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /

    # Match the host, if you wish
    #RewriteCond %{HTTP_HOST} ^localhost$

    RewriteRule classifieds/activate/(.*) index.php?page=activate&extra=$1 [L]
</IfModule>

In case you want any query string parameter to be passed, you need to add the QSA flag to the end of the rewrite rule.

You can test it online, if you wish.

If you need a more generic rewrite rule to rewrite the second segment of the URI (activate in this case) to the page parameter, here's what you need:

RewriteRule classifieds/(.*)/(.*) index.php?page=$1&extra=$2 [L]

You can be more specific about what characters you want to expect; swapping (.*) with something like ([0-9A-Za-z]) or (\w) to accept only alphanumeric values will do.