如何在单个域名下为多个Web应用配置mod_rewrite规则?
Apache .htaccess 重写规则配置方案
没问题,我来帮你搞定这个配置——刚接触Apache的话,确实容易对rewrite规则犯懵,咱们一步步来。
首先得确认两个前提条件(这俩是规则生效的关键):
- 你的Apache已经启用了
mod_rewrite模块:Linux系统可以用sudo a2enmod rewrite命令开启,然后重启Apache;Windows则需要在httpd.conf里把#LoadModule rewrite_module modules/mod_rewrite.so这行的注释去掉,再重启服务。 - 你的Apache站点配置中,
root-folder对应的<Directory>块里设置了AllowOverride All,这样.htaccess里的规则才能被Apache识别。
接下来,把下面的代码保存为.htaccess文件,直接放在你的root-folder根目录下就行:
# 开启重写引擎 RewriteEngine On # 排除真实存在的文件/目录(比如图片、脚本、已有的页面),避免干扰正常访问 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # 访问 domain.com/app0 或 domain.com/app0/ 时,跳转到 another_app0_folder 下的index.html RewriteRule ^app0/?$ another_app0_folder/index.html [L] # 访问 domain.com/app1 或 domain.com/app1/ 时,跳转到 another_app1_folder 下的index.html RewriteRule ^app1/?$ another_app1_folder/index.html [L] # 访问 domain.com/app2 或 domain.com/app2/ 时,跳转到 another_app2_folder/public 下的index.php RewriteRule ^app2/?$ another_app2_folder/public/index.php [L] # 根路径直接指向root下的index.html(Apache默认会自动找,但明确写出来更稳妥) RewriteRule ^$ index.html [L]
额外说明(按需调整):
- 如果你的
app2是需要处理动态路由的应用(比如PHP框架、单页应用),希望所有domain.com/app2/xxx这样的子路径都交给index.php处理,可以把app2的规则改成:RewriteRule ^app2/(.*)$ another_app2_folder/public/index.php [L] - 如果你不想用
app0/app1这种简化路径,而是直接用文件夹名称访问(比如domain.com/another_app0_folder),那其实Apache默认就能直接访问里面的index.html,不需要额外写规则——除非你想隐藏文件夹名称。
内容的提问来源于stack exchange,提问作者noob e tah
相关产品推荐
相关产品推荐

