Apache .htaccess重写URL问题:动态转静态地址求助
Hey there! Let’s get that URL rewrite sorted out so www.example.com/username properly maps to www.example.com/userprofile.php?username=username without exposing the original query string.
First, make sure your server has mod_rewrite enabled (most shared hosts have this on by default, but if not, you might need to check with your host or confirm RewriteEngine On is at the top of your .htaccess file).
Here’s the correct set of rules to add to your .htaccess file (replace any existing rewrite rules related to this profile page):
RewriteEngine On # Rewrite user profile URLs: www.example.com/username → userprofile.php?username=username # Only rewrite if the requested path isn't an actual file or directory RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^/]+)$ userprofile.php?username=$1 [L,QSA]
Let me break down what each part does:
RewriteEngine On: Enables the rewrite module (critical if it’s not already active).- The two
RewriteCondlines: Ensure we don’t rewrite requests for real files (like images, CSS) or directories—this prevents breaking your site’s existing resources. RewriteRule ^([^/]+)$: Matches any URL path that’s a single segment (no slashes, perfect for usernames). The([^/]+)captures the username as a reusable group.userprofile.php?username=$1: Maps the captured username to theusernameGET parameter in your original script.[L,QSA]:Ltells Apache this is the last rule to process for this request (avoids conflicts), andQSApreserves any additional query parameters if you ever need them (e.g.,www.example.com/username?foo=barwould still passfoo=barto the script).
Common Fixes for Your Original Issue
If you were seeing the GET parameter output but the rewrite wasn’t masking the URL, here are likely culprits:
- Missing the
RewriteCondchecks: Without these, Apache might rewrite theuserprofile.phpfile itself, causing a loop that exposes the query string. - Forgetting the
[L]flag: This can lead to other rules interfering with the rewrite. - Incorrect regex: If your original rule used a broader pattern (like
.*), it might have matched too much and caused unexpected behavior.
Once you update your .htaccess, test by visiting www.example.com/yourtestusername—the address bar should stay clean, and your script should still receive the username parameter correctly.
内容的提问来源于stack exchange,提问作者testuser

