繁体   English   中英

.htaccess RewriteRule 到路径而不更改 URL

[英].htaccess RewriteRule to path without changing URL

所以,我有这个问题:

  1. 基本网站位于http://example.com/
  2. 第二个网站位于http://example.com/web2/
  3. 人们向第二个网站发出各种请求,如http://example.com/myWeb/pg1http://example.com/web2/pg2

最近,由于其他一些问题,我需要为第二个网站创建一个自定义的新路径,但也要保持第一个网站正常工作。

想法是允许用户通过以下两个地址访问第二个网站:

  • http://example.com/web2/
  • http://example.com/alternative-url-web2/

文件夹/web2/实际上存在于服务器上,但是如何模拟文件夹/alternative-url-web2/并将请求“重定向”到/web2/

请注意,我不希望浏览器上的 URL 发生变化,这必须是“无声重定向”。 而且我还确保第二个网站不会重定向所有其他请求,例如http://example.com/other

谢谢你。


更新

根据@anubhava,我可以通过添加我的.htaccess来简单地解决这个问题:

Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteRule ^alternative-url-web2(/.*|)$ /web2$1 [L,NC]

这可能工作正常,但我注意到以下几点:

  • http://ex.com/alternative-url-web2被重定向到http://ex.com/web2/ (更改浏览器 URL);
  • http://ex.com/alternative-url-web2/被重定向到http://ex.com/ (更改浏览器 URL);
  • http://ex.com/alternative-url-web2/someRequest工作正常并且不会更改浏览器 URL;
  • http://ex.com/alternative-url-web2/index.php工作正常并且不会更改浏览器 URL;

网站注意事项:

/web2/有一个.htaccess可能会导致上面的有线重定向行为......所以这里是文件内容:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ - [NC,L]
    RewriteRule ^(data/|js/|styles/|install/|favicon\.ico|crossdomain\.xml|robots\.txt) - [NC,L]
    RewriteRule ^.*$ index.php [NC,L]
</IfModule>

index.php的内部 RewriteRule 会导致这一切吗? 如果是,我该如何解决?

这是一个非常简单的重写。 在文档根目录的 htaccess 文件中,只需添加以下内容:

RewriteEngine On
RewriteRule ^alternative-url-web2/?(.*)$ /web2/$1 [L]

与重定向不同,它使浏览器/客户端向新 URL 发送新请求(从而更改浏览器位置栏中的内容),重写完全发生在服务器端。

通过httpd.conf启用 mod_rewrite 和 .htaccess,然后将此代码放在DOCUMENT_ROOT目录下的.htaccess

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteRule ^alternative-url-web2(/.*|)$ /web2$1 [L,NC]

替代代码:

RewriteRule ^alternative-url-web2/?$ /web2/ [L,NC]
RewriteRule ^alternative-url-web2/(.+)$ /web2/$1 [L,NC]

暂无
暂无

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

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