Apache中实现特定路径下PHP动态通配符子域名配置求助
动态子域名访问Apache配置解决方案
我需要让http://localhost/example/category这类路径支持user1.localhost/example/category、user2.localhost/example/category这类任意动态子域名访问,但目前只有localhost首页能实现该功能,以下是我已尝试的配置:
已尝试的配置
httpd-vhosts.conf
<VirtualHost *:80> ServerAdmin admin@example.com DocumentRoot "C:/wamp64/www" ServerName localhost ServerAlias *.localhost ErrorLog "logs/localhost-error.log" CustomLog "logs/localhost-access.log" common <Directory "C:/wamp64/www"> Options Indexes FollowSymLinks Includes ExecCGI AllowOverride All Require all granted </Directory> </VirtualHost>
hosts文件
127.0.0.1 localhost 127.0.0.1 *.localhost ::1 localhost
解决步骤
修复hosts的通配符问题
Windows系统的hosts文件不支持*.localhost这种通配符写法,要么手动添加每个子域名的映射,要么借助第三方DNS工具(比如Acrylic DNS Proxy)实现通配解析。测试场景下手动添加更直接:127.0.0.1 localhost 127.0.0.1 user1.localhost 127.0.0.1 user2.localhost ::1 localhost ::1 user1.localhost ::1 user2.localhost开启Apache的rewrite模块
打开httpd.conf,找到LoadModule rewrite_module modules/mod_rewrite.so这一行,去掉前面的注释符号#,启用该模块。添加URL重写规则
在网站根目录C:/wamp64/www下创建或修改.htaccess文件,添加以下规则,确保动态子域名的请求能正确映射到目标路径:RewriteEngine On # 跳过localhost本身的请求 RewriteCond %{HTTP_HOST} !^localhost$ [NC] # 匹配子域名部分 RewriteCond %{HTTP_HOST} ^([a-zA-Z0-9-]+)\.localhost$ [NC] # 直接转发到原路径,无需额外处理时使用 RewriteRule ^(.*)$ $1 [L]如果需要把子域名作为参数传递给后端应用(比如PHP),可以改用以下规则:
RewriteEngine On RewriteCond %{HTTP_HOST} !^localhost$ [NC] RewriteCond %{HTTP_HOST} ^([a-zA-Z0-9-]+)\.localhost$ [NC] # 将子域名作为subdomain参数传递,QSA保留原有请求参数 RewriteRule ^(.*)$ $1?subdomain=%1 [QSA,L]重启Apache验证
修改完所有配置后,重启WAMP中的Apache服务,访问user1.localhost/example/category测试是否正常访问。
内容的提问来源于stack exchange,提问作者jamazzz
相关产品推荐
相关产品推荐

