Using htaccess rewrite to make a subdirectory be its own root for root relative path requests

寵の児 提交于 2019-12-14 03:58:28

问题


Can I use htaccess to capture requests from a certain subdirectory and make that directory use itself as the root directory for any root relative path requests? For example if I have...

http://www.example.com/subFIXED/subANY/restofpath

...where subFIXED is always the same directory, subANY is any immediate subdirectory of subFIXED, and I want a redirection of all href/src requests from any file under subANY to use subANY as the 'root' (sort of like a subdomain), in effect having root level requests use this as the root directory level:

http://www.example.com/subFIXED/subANY/

Instead of this:

http://www.example.com/

I'm assuming I can put an htaccess file in subFIXED to handle all calls coming from anything under any subANY, but not being very familiar with htaccess rewriting, variables, etc., I can't figure out how to capture which subANY directory is making the root level request and then use that capture to make a rewrite to consider that directory the root level of any root relative path requests from it.

Thanks for your help


回答1:


Euhm, .htaccess? It would have to rely on the extremely unreliable HTTP_REFERER, no thanks.

Add a <base> element in your HTML & be done. http://www.w3schools.com/tags/tag_base.asp


Edit: relative to root ("/foo") should also be accounted for, so after fixing relative paths with <base>:

.htaccess (extremely unreliable because switching of subpath is nigh impossible, and HTTP_REFERER's are extremely unreliable. in short: don't use)

RewriteCond %{HTTP_REFERER} ^.*://[^/]+/subFIXED/([^/]+)/
RewriteCond %{REQUEST_URI}  !^/subFIXED
RewriteRule ^(.*)$ /subFIXED/%1/$1 [R=301,L,QSA] //drop the R=301 if POSTing, but url will not show the 'correct' one in that case

Pitfalls:

  1. POSTing is awkward (cannot redirect & preserve POST, so will have to land 'normally', which will make the REFERER on subsequent requests useless / false
  2. Referer is often not sent
  3. Switching to other 'subAny' from any other 'subAny' is impossible when sending REFERER

More viable solutions:

  1. Postprocess each and every request with script on the server, adding a dot (.) to every reference (href/src) that starts with '/'.
  2. The previous one can be done with clientside javascript, but this is not recommendable because all links for searchbots & browsers with js disabled would break
  3. Make an actual subdomain, this is just a hassle.

In short, no desirable solutions except for making actual subdomains. What is the exact problem you're trying to solve that you need this 'fixed rootpath' solution? There could be others that don't involve this much hassle.



来源:https://stackoverflow.com/questions/2982205/using-htaccess-rewrite-to-make-a-subdirectory-be-its-own-root-for-root-relative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!