Search code examples
apache.htaccesshttp-redirectmod-rewritevhosts

How to Configure rewrite rule , so that the request will route to server name even if alias name is used in URL


We have a virtual host file with below content,

    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>

We can access the application using server name and alias name.

  1. http://example.domain.com which expands to http://example.domain.com/StartPage/startpage.jsp
  2. http://example which expands to http://example/StartPage/startpage.jsp

Now , the requirement is to redirect the url to server name when we use server alias name as below

http://example which expands to http://example.domain.com/StartPage/startpage.jsp

Can some one help me to modify the vhost file to make this work.


Solution

  • This probably is what you are looking for:

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

    The rule must follow the line with the condition immediately. And the redirection should be done prior to other redirections.

    It is a good idea to start out with a 302 redirection and only change that to a 301 once you are sure everything works as desired.

    If you prefer not to keep the path of the requested URL, but always redirect to a fixed path prefix then that should be fine:

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