rewriting url to hide real page path

2019-04-29 19:46发布

问题:

I recently with the help of SO solved my htaccess rewriterule issue:

Reuse subdomain in a rewrite rule

The result is that when somebody enters

whatever.example.com/anypage

in the adress bar, the htaccess automatically redirects to

whatever.example.com/somepath/whatever/anypage

What I wish to do is to find a way to just show whatever.example.com/anypage in the adress bar with the content of whatever.example.com/somepath/whatever/anypage displayed.

In the post I mentioned earlier, Jon Lin clearly mentions the following:

redirects always change what's in the browser's URL address bar

However I know some very frequent cases of url rewritting that would show in the adress bar let's say, for instance:

example.com/article-1-15

but actually showing the content of

example.com/somepath/somepage.php?article=1&otherparam=15

How could this apply to my case? I really wish to have a tiny url but it seems I missed something.

回答1:

You may try something like this:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI}  ^/([^/]+)$
RewriteRule .*  http://whatever.example.com/somepath/whatever/%1 [L]

It will map:

http://whatever.example.com/anypage

To a resource at:

http://whatever.example.com/somepath/whatever/anypage

showing always in the browser's address bar:

http://whatever.example.com/anypage

UPDATED

If whatever is dynamic and is the same in the substitution URI, here is another option:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST}  ([^/]+)\.example\.com.*
RewriteCond %{REQUEST_URI}  ^/([^/]+)$
RewriteRule .*  http://%1.example.com/somepath/%1/%2 [L]

This will work as long as both "whatever" in the substitution path are the same. If they are not, the last "whatever" has to be hardcoded, like this:

RewriteRule .*  http://%1.example.com/somepath/whatever/%2 [L]

There is no other way as the incoming URL doesn't have it.