如何配置重写规则,以便即使在 URL 中使用别名,请求也将路由到服务器名称

问题描述

我们有一个包含以下内容的虚拟主机文件

    NameVirtualHost *:8888
    <VirtualHost *:8888>
      ServerName example.domain.com
      ServerAlias example
      DocumentRoot /opt/weblogic/product/virtualhosts/example.domain.com/htdocs
      ErrorLog /opt/weblogic/product/virtualhosts/example.domain.com/logs/error_log
      RewriteEngine On
      #RewriteRule  ^/?$ %{REQUEST_URI}/StartPage [R,L]
      RewriteOptions Inherit
      DirectoryIndex index.html startpage.jsp
      <Directory />
        Require all granted
      </Directory>
    </VirtualHost>

我们可以使用服务器名称和别名访问应用程序。

  1. http://example.domain.com 扩展为 http://example.domain.com/StartPage/startpage.jsp
  2. http://example 扩展为 http://example/StartPage/startpage.jsp

现在,当我们使用服务器别名时,要求将url重定向到服务器名称

http://example 扩展为 http://example.domain.com/StartPage/startpage.jsp

有人可以帮我修改 vhost 文件以使其正常工作。

解决方法

这可能就是您要找的:

RewriteCond %{HTTP_HOST} ^example$
RewriteRule ^ https://example.domain.com%{REQUEST_URI} [R=301,QSA,END]

规则必须紧跟条件行。并且重定向应该在其他重定向之前完成。

从 302 重定向开始是一个好主意,只有在确定一切正常后才将其更改为 301。

如果您不想保留所请求 URL 的路径,而是始终重定向到固定路径前缀,那应该没问题:

RewriteCond %{HTTP_HOST} ^example$
RewriteRule ^ https://example.domain.com/StartPage [R=301,END]