.htaccess动态URL重写及子域名目录访问配置求助
Absolutely, your requirements are totally feasible! Let's break down the solution step by step with the right .htaccess configurations—no redirects needed for the dynamic URL rewrite, and proper access restriction for the specified directories.
1. Dynamic URL Rewrite (Silent Internal Mapping)
First, we’ll set up an internal rewrite so http://localhost/example silently points to http://localhost/verload.php?name=example without any visible URL change. Add this code to your root .htaccess file:
RewriteEngine On # Skip rewriting for actual files/directories (preserves access to assets like CSS, JS, images) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Map the requested path segment to the "name" parameter in verload.php RewriteRule ^([a-zA-Z0-9_-]+)$ verload.php?name=$1 [L]
Key Details:
RewriteEngine Onenables Apache’s rewrite module (ensure mod_rewrite is enabled in your Apache setup first!).- The two
RewriteCondlines prevent rewriting requests for real files or directories, avoiding conflicts with your existing site assets. - The
RewriteRuleuses a regex ([a-zA-Z0-9_-]+) to capture the path segment (likeexample). Adjust this regex if your "name" values include special characters. The[L]flag tells Apache to stop processing further rules if this one matches.
2. Restrict admin/loader Directories to admin.localhost
Next, we’ll block access to these directories unless the request comes from http://admin.localhost/. Add this right after the rewrite rules above:
# Block access to admin/loader directories unless using admin.localhost RewriteCond %{HTTP_HOST} !^admin\.localhost$ [NC] RewriteRule ^(admin|loader)/ - [F,L]
Key Details:
RewriteCond %{HTTP_HOST} !^admin\.localhost$ [NC]checks if the requested hostname is notadmin.localhost(the[NC]flag makes the check case-insensitive).- If the condition is met, the
RewriteRulematches any request starting withadmin/orloader/and returns a403 Forbiddenresponse ([F]flag), stopping further processing with[L].
Critical Pre-Requisites:
- Enable Apache’s
mod_rewritemodule: On Linux systems, runsudo a2enmod rewritethen restart Apache withsudo systemctl restart apache2. On Windows, uncomment theLoadModule rewrite_moduleline in your Apache config file. - Ensure your Apache site configuration has
AllowOverride Allset for the root directory—this lets.htaccessfiles take effect. - Add an entry to your local
hostsfile to mapadmin.localhostto127.0.0.1:
(On Windows, this file is at127.0.0.1 admin.localhostC:\Windows\System32\drivers\etc\hosts; on Linux/macOS, it’s at/etc/hosts.)
That’s all! With these configurations, your dynamic URL will work as a silent internal rewrite, and the admin/loader directories will only be accessible via the admin.localhost subdomain.
内容的提问来源于stack exchange,提问作者DEVICARUS

