简体   繁体   English

htaccess中301重定向的相对URL重写

[英]Relative URL for 301 redirect in htaccess rewrite

I used to have a documentation file at https://example.com/myapp/doc/file.html , but I have now decided to host the documentation at https://example.com/myapp/doc/ . 我曾经在https://example.com/myapp/doc/file.html上有一个文档文件,但是现在我决定将文档托管在https://example.com/myapp/doc/ Note that the path can be different, eg http://customer.com:8080/foo/bar/myapp/doc/file.html . 请注意,路径可以不同,例如http://customer.com:8080/foo/bar/myapp/doc/file.html

How can I use htaccess to redirect to the correct directory? 如何使用htaccess重定向到正确的目录? My tries were: 我的尝试是:

RewriteEngine On
RewriteRule ^file\.html$ "" [R=301]

This puts a filesystem path in the URL and is totally unsuitable. 这会将文件系统路径放在URL中,并且完全不合适。 If I wanted an internal redirect it would probably work, but I explicitly want a 301. 如果我想要内部重定向,它可能会起作用,但我明确希望使用301。

RewriteEngine On
RewriteRule ^file\.html$ "%{REQUEST_SCHEME}://%{HTTP_HOST}/myapp/doc/" [R=301]

This works, but only when my app is installed into the URL root. 这有效,但仅当我的应用程序安装到URL根目录中时。 When a customer puts it into /foo/bar , it fails. 当客户将其放入/foo/bar ,它将失败。

How can I 301-redirect to the current directory? 如何301重定向到当前目录?

Following code should work from any where to redirect file.html in current directory to current directory itself without any hardcoding of paths. 下面的代码应该可以在任何位置将当前目录中的file.html重定向到当前目录本身,而无需对路径进行任何硬编码。 It compares REQUEST_URI variable (which is complete path) with the URI matched by RewriteRule (which is relative to current path) and gets differential in %{ENV:BASE} variable. 它将REQUEST_URI变量(完整的路径)与RewriteRule匹配的URI(相对于当前路径)进行比较,并获取%{ENV:BASE}变量的差异。

RewriteEngine On

# find rewrite base dynamically
RewriteCond $0#%{REQUEST_URI} ^([^#]*)#(.*)\1$
RewriteRule ^.*$ - [E=BASE:%2]

RewriteRule ^file\.html$ %{ENV:BASE} [L,R=301,NC]

For example, it will perform following redirects: 例如,它将执行以下重定向:

  • /foo/bar/myapp/doc/file.html to /foo/bar/myapp/doc/ /foo/bar/myapp/doc/file.html/foo/bar/myapp/doc/
  • /myapp/doc/file.html to /myapp/doc/ /myapp/doc/file.html/myapp/doc/
  • /some/path/file.html to /some/path/ /some/path/file.html/some/path/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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