.htaccess rewrite subdomain to directory

前端 未结 8 1988
不思量自难忘°
不思量自难忘° 2020-11-22 10:26

Is it possible to use .htaccess to rewrite a sub domain to a directory?

Example:

  • http://sub.domain.com/

shows the content of

8条回答
  •  一个人的身影
    2020-11-22 11:15

    You can use the following rule in .htaccess to rewrite a subdomain to a subfolder:

    RewriteEngine On
    
     # If the host is "sub.domain.com"
     RewriteCond %{HTTP_HOST} ^sub.domain.com$ [NC]
     # Then rewrite any request to /folder
     RewriteRule ^((?!folder).*)$ /folder/$1 [NC,L]
    

    Line-by-line explanation:

      RewriteEngine on
    

    The line above tells the server to turn on the engine for rewriting URLs.

      RewriteCond %{HTTP_HOST} ^sub.domain.com$ [NC]
    

    This line is a condition for the RewriteRule where we match against the HTTP host using a regex pattern. The condition says that if the host is sub.domain.com then execute the rule.

     RewriteRule ^((?!folder).*)$ /folder/$1 [NC,L]
    

    The rule matches http://sub.domain.com/foo and internally redirects it to http://sub.domain.com/folder/foo.

    Replace sub.domain.com with your subdomain and folder with name of the folder you want to point your subdomain to.

提交回复
热议问题