Apache服务器中.htaccess文件的实用配置示例集锦

2019-10-13 22:54:03王旭

7. 阻止WordPress博客的垃圾评论
还在为垃圾评论头疼吗?你可以用Akismet插件来解决这个问题,但是.htaccess文件来的更直接:阻止垃圾评论机器人访问wp-comments-post.php文件

<IfModule mod_rewrite.c> 
RewriteEngine On 
RewriteCond %{REQUEST_METHOD} POST 
RewriteCond %{REQUEST_URI} .wp-comments-post.php* 
RewriteCond %{HTTP_REFERER} !.*yourdomainname.* [OR] 
RewriteCond %{HTTP_USER_AGENT} ^$ 
RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L] 
</IfModule> 

8.重定向不同的feed格式到统一的格式
很多年前,有很多不同的feed格式,例如RSS、Atom、RDF等等。但是现在RSS已经占了绝对的主导地位。下面这段代码可以让你重定向不同的feed格式到同一个feed。这段代码可以直接在WordPress博客上使用。

<IfModule mod_alias.c> 
 RedirectMatch 301 /feed/(atom|rdf|rss|rss2)/?$ http://example.com/feed/ 
 RedirectMatch 301 /comments/feed/(atom|rdf|rss|rss2)/?$ http://example.com/comments/feed/ 
</IfModule> 

9. 配置网站的HTML5视频
HTML5为我们带来了不用Flash的视频播放功能,但是你必须配置你的服务器来提供最新的HTML5视频播放功能。

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_URI} !=/favicon.ico 
AddType video/ogg .ogv 
AddType video/ogg .ogg 
AddType video/mp4 .mp4 
AddType video/webm .webm 
AddType application/x-shockwave-flash swf 

10. 记录PHP错误
在页面上显示PHP错误是很尴尬的事情,也不安全,下面这段代码可以把PHP错误记录到.log文件中而不在页面显示。

# display no errs to user 
php_flag display_startup_errors off 
php_flag display_errors off 
php_flag html_errors off 
# log to file 
php_flag log_errors on 
php_value error_log /location/to/php_error.log 

11. 在JavaScript代码中运行PHP
在JS中插入PHP代码有时候是很有用的,例如读取数据库。下面这段代码可以让你在JS中运行PHP。

AddType application/x-httpd-php .js 
AddHandler x-httpd-php5 .js 
 
<FilesMatch ".(js|php)$"> 
SetHandler application/x-httpd-php 
</FilesMatch> 

12. 404页面跳转,跳转到404.php,根据url记录不存在页面的路径

<IfModule mod_rewrite.c> 
RewriteEngine On 
 
RewriteCond %{REQUEST_FILENAME} !-f  
RewriteCond %{REQUEST_FILENAME} !-d  
RewriteCond %{QUERY_STRING} !^$ 
RewriteRule ^/?(.*)$ /404.php?url=%{HTTP_HOST}%{REQUEST_URI}?%{QUERY_STRING} [NC]  
 
RewriteCond %{REQUEST_FILENAME} !-f  
RewriteCond %{REQUEST_FILENAME} !-d  
RewriteCond %{QUERY_STRING} ^$ 
RewriteRule ^/?(.*)$ /404.php?url=%{HTTP_HOST}%{REQUEST_URI} [NC]  
 
</IfModule>