请求优化.htaccess文件重写规则及相关配置的专业方案
Hey there! Let's get that messy .htaccess file cleaned up and optimized. Based on the four key areas you outlined (redirects, CSP, content delivery, MIME types) plus the PHP settings you shared, here's a structured, production-ready solution with clear comments to keep things maintainable.
Core Server & PHP Security/Configuration
First, let's tidy up the base settings you included, plus add a few security hardening tweaks:
# Hide server version information to reduce attack surface ServerTokens Prod ServerSignature Off # Increase PHP input variable limits (matches your original values) php_value max_input_vars 40000 php_value suhosin.get.max_vars 40000 php_value suhosin.post.max_vars 40000 php_value suhosin.request.max_vars 40000
Note: If your host uses PHP-FPM instead of mod_php, these directives might need to go in a php.ini or user.ini file instead.
1. Redirect Rules (Organized & Secure)
Group redirects by purpose for clarity. Here are common, high-impact redirects you can adapt to your needs:
# Enable rewrite engine RewriteEngine On # Redirect HTTP to HTTPS (enforce secure connections) RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # Redirect www to non-www (flip this if you prefer www as your primary domain) RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ https://%1/$1 [L,R=301] # Custom 404 error page (update the path to match your site's 404 file) ErrorDocument 404 /404.html
Tip: Use R=302 for temporary redirects and R=301 for permanent ones. Test redirects with curl or a browser dev tools to avoid loops.
2. Content Security Policy (CSP) - Balanced Security & Functionality
A restrictive CSP helps prevent XSS attacks. Start with this template and adjust sources to match your site's resources:
# Content Security Policy (customize sources to fit your site's assets) Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; # Remove 'unsafe-inline'/'unsafe-eval' if you can avoid inline scripts style-src 'self' 'unsafe-inline'; # Remove 'unsafe-inline' once you use external stylesheets exclusively img-src 'self' data: https:; font-src 'self' https:; object-src 'none'; frame-src 'none'; upgrade-insecure-requests;" # Optional: Use Report-Only mode first to test without breaking your site # Header set Content-Security-Policy-Report-Only "default-src 'self'; ..."
Key: Replace broad sources like https: with specific domains (e.g., https://cdn.yoursite.com) for tighter security. Avoid unsafe-inline/unsafe-eval unless absolutely necessary.
3. Content Delivery Optimization
Speed up your site with compression, caching, and resource optimization:
# Enable Gzip compression for text-based assets <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/plain text/html text/xml text/css application/xml application/xhtml+xml application/rss+xml application/javascript application/x-javascript </IfModule> # Enable browser caching for static assets <IfModule mod_expires.c> ExpiresActive On # Images (long cache since they rarely change) ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/webp "access plus 1 year" # CSS/JS (monthly cache to balance freshness and performance) ExpiresByType text/css "access plus 1 month" ExpiresByType application/javascript "access plus 1 month" # HTML (daily cache since content may update frequently) ExpiresByType text/html "access plus 1 day" </IfModule> # Disable ETags to prevent caching conflicts between server and browser FileETag None # Set strict cache control for static resources <FilesMatch "\.(jpg|jpeg|png|gif|webp|css|js|ico|svg)$"> Header set Cache-Control "public, max-age=31536000, immutable" </FilesMatch>
4. MIME Type Declarations
Add missing or updated MIME types for modern web assets:
# Modern MIME types for better browser compatibility AddType image/webp .webp AddType image/svg+xml .svg AddType application/font-woff2 .woff2 AddType application/javascript .js AddType text/css .css
Here's all the above combined into a single, clean, maintainable file:
# -------------------------- # Core Server & PHP Settings # -------------------------- ServerTokens Prod ServerSignature Off php_value max_input_vars 40000 php_value suhosin.get.max_vars 40000 php_value suhosin.post.max_vars 40000 php_value suhosin.request.max_vars 40000 # -------------------------- # Redirect Rules # -------------------------- RewriteEngine On # HTTP to HTTPS RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # www to non-www RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ https://%1/$1 [L,R=301] ErrorDocument 404 /404.html # -------------------------- # Content Security Policy # -------------------------- Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https:; object-src 'none'; frame-src 'none'; upgrade-insecure-requests;" # -------------------------- # Content Delivery Optimization # -------------------------- <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/plain text/html text/xml text/css application/xml application/xhtml+xml application/rss+xml application/javascript application/x-javascript </IfModule> <IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/webp "access plus 1 year" ExpiresByType text/css "access plus 1 month" ExpiresByType application/javascript "access plus 1 month" ExpiresByType text/html "access plus 1 day" </IfModule> FileETag None <FilesMatch "\.(jpg|jpeg|png|gif|webp|css|js|ico|svg)$"> Header set Cache-Control "public, max-age=31536000, immutable" </FilesMatch> # -------------------------- # MIME Type Declarations # -------------------------- AddType image/webp .webp AddType image/svg+xml .svg AddType application/font-woff2 .woff2 AddType application/javascript .js AddType text/css .css
Final Notes
- Always test changes on a staging environment first to avoid breaking your live site.
- Check if your hosting provider has any specific restrictions (e.g., mod_deflate might be enabled by default).
- For the CSP, use the Report-Only mode initially to collect violations before enforcing the policy.
内容的提问来源于stack exchange,提问作者Sarvesh Sonawane

