如何在.htaccess中移除文件扩展名后的斜杠与反斜杠?
Hey there, I totally get why this is frustrating—let's get this sorted out quickly!
Why the styles break
When you add a trailing / or \ to about.php (making it about.php/ or about.php\), your browser treats about.php/ like a directory instead of a file. That means any relative paths in your HTML (like css/style.css or js/script.js) will try to load from about.php/css/style.css instead of the root directory, which is why your styles and layout fall apart.
The .htaccess solution
Add these rules to your .htaccess file in the root of your website to automatically remove those trailing slashes/backslashes and redirect users to the correct URL:
# Enable URL rewriting RewriteEngine On # Remove trailing forward slashes after .php files RewriteRule ^(.+\.php)/+$ $1 [R=301,L,NC] # Remove trailing backslashes after .php files RewriteRule ^(.+\.php)\\+$ $1 [R=301,L,NC]
What each part does:
RewriteEngine On: Turns on Apache's rewrite module (required for these rules to work).R=301: Sends a permanent redirect, which is good for SEO and ensures browsers cache the correct URL.L: Stops processing further rules once this one matches, so we don't run into conflicts.NC: Makes the rule case-insensitive (covers edge cases likeABOUT.PHP/if that ever comes up).- The regex patterns target any PHP file followed by one or more trailing slashes/backslashes, and redirect to the same file without those extra characters.
Quick checks:
- Make sure your Apache server has
mod_rewriteenabled (most hosts have this on by default, but if not, you might need to ask your hosting provider or enable it in your server config). - Ensure your site's directory allows
.htaccessoverrides (your server config should haveAllowOverride Allset for the directory).
Once you add these rules, visiting www.domain.com/about.php/ or www.domain.com/about.php\ will automatically redirect to www.domain.com/about.php, and your styles will load correctly again.
内容的提问来源于stack exchange,提问作者Ian

