最近學爬蟲。發(fā)現httppost請求目標網站會出現405 狀態(tài)碼,原因為 Apache、IIS、Nginx等絕大多數web服務器,都不允許靜態(tài)文件響應POST請求
所以將post請求改為get請求即可
Apache、IIS、Nginx等絕大多數web服務器,都不允許靜態(tài)文件響應POST請求,否則會返回“HTTP/1.1 405 Method not allowed”錯誤。
1.首先看到的頁面是nginx返回的頁面,得知錯誤要從nginx上來解決
返回頁面:
<html>
<head><title>405 Not Allowed</title></head>
<body bgcolor="white">
<center><h1>405 Not Allowed</h1></center>
<hr><center>nginx/1.0.11</center>
</body>
</html>
2.上網查資料,原來因為這里請求的靜態(tài)文件采用的是post方法,nginx是不允許post訪問靜態(tài)資源。題話外,試著post訪問了下www.baidu.com發(fā)現頁面也是報錯
3.現貼出三種解決方式
1.將405錯誤指向成功(我采用的這種方法解決的問題)
靜態(tài)server下的location加入error_page 405 =200 $uri;
location ~ ^/better/.*\.(htm|html|gif|jpg|jpeg|png|ico|rar|css|js|zip|txt|flv|swf|doc|ppt|xls|pdf|json|ico|htc)$ {
<span style="white-space:pre"> </span>root D:/code/BetterjrWeb;
<span style="white-space:pre"> </span>error_page 405 =200 $uri;
}
2.修改nginx下src/http/modules/ngx_http_static_module.c文件
if (r->method & NGX_HTTP_POST) {
return NGX_HTTP_NOT_ALLOWED;
}
這一段注釋掉,重新編譯,不要make install編譯生成的nginx文件復制到sbin下 重啟nginx
3.修改錯誤界面指向(網上多流傳這種方式,但是沒有改變請求方法,所以行不通,所以采用以下方法)
upstream static_backend {
server localhost:80;
}
server {
listen 80;
# ...
error_page 405 =200 @405;
location @405 {
root /srv/http;
proxy_method GET;
proxy_pass http://static_backend;
}
}
例1:用Linux下的curl命令發(fā)送POST請求給Apache服務器上的HTML靜態(tài)頁
[root@new-host ~]# curl -d 1=1 http://www.linuxidc.com/index.html
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<HTML><HEAD>
<TITLE>405 Method Not Allowed</TITLE>
</HEAD><BODY>
<H1>Method Not Allowed</H1>
The requested method POST is not allowed for the URL /index.html.<P>
<HR>
<ADDRESS>Apache/1.3.37 Server at www.linuxidc.com Port 80</ADDRESS>
</BODY></HTML>
例2:用Linux下的curl命令發(fā)送POST請求給Nginx服務器上的HTML靜態(tài)頁
[root@new-host ~]# curl -d 1=1 http://www.linuxidc.com/index.htm
<html>
<head><title>405 Not Allowed</title></head>
<body bgcolor="white">
<center><h1>405 Not Allowed</h1></center>
<hr><center>nginx/0.5.35</center>
</body>
</html>
但在有些應用中,需要使靜態(tài)文件能夠響應POST請求。
對于Nginx,可以修改nginc.conf配置文件,改變“405錯誤”為“200 ok”,并配置location來解決,方法如下:
server
{
listen 80;
server_name domain.s135.com;
index index.html index.htm index.php;
root /opt/htdocs;
if (-d $request_filename)
{
rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
}
error_page 405 =200 @405;
location @405
{
root /opt/htdocs;
}
location ~ .*\.php?$
{
include conf/fcgi.conf;
fastcgi_pass 127.0.0.1:10080;
fastcgi_index index.php;
}
}