python编程(webpy + gunicorn + nginx部署)

之前虽然也用nginx + uwsgi + webpy的方法部署过网站,但是用了gunicorn之后,发现用这种方法部署网站更为简单。下面我详细描述一下如何用这种方法进行网站部署。

1、准备server.py

和uwsgi部署的时候一样,这里仅仅需要设置一个application就可以了。

#!/usr/bin/python
import web

urls = ('/', 'Hello')

class Hello(object):
    def GET(self):
        return 'Hello world'

app = web.application(urls, globals())  
application = app.wsgifunc()

2、安装gunicorn

安装gunicorn的方法非常简单,在ubuntu下面一条命令就可以解决,

sudo apt-get install gunicorn

3、用gunicorn启动server.py文件

启动的时候注意,最后一个选项是由文件名+wsgifunc组成的。同时,我们在选项中添加了gevent的属性,gunicorn本身支持gevent机制,可以有效提高server的性能。

gnicorn -b 127.0.0.1:8080 --worker-class gevent server:application

4、用浏览器做测试

这个时候不出意外,你已经可以用127.0.0.1:8080访问我们的网站了。

5、准备nginx.conf文件

通常为了利用nginx做static文件加速,或者利用nginx做均衡负载,我们常常需要另外安装一下nginx软件。因此,此时nginx.conf必须准备好。当然,为了简单起见,我们这里只做一个代理就可以了,整个conf文件内容如下,

worker_processes 1;

events{
    worker_connections 1024;
}

http{

    sendfile on;
    keepalive_timeout 65;

    server {
        listen       80;
        server_name  localhost;

        location / {

            proxy_pass http://127.0.0.1:8080;
        } 
    }

}

6、重启启动nginx

nginx.conf准备好后,这个时候先将它copy到/etc/nginx目录下。接下来,我们需要重新启动nginx软件,一个命令就可以了,

service nginx restart

7、用浏览器测试80端口

有了nginx做代理,这个时候就可以用浏览器访问127.0.0.1了,因为一般网站默认用80做端口,所以没有意外的话,这个时候你就可以看到webpy给出的打印消息了。

Ubuntu下配置nginx反向代理服务器

Nginx是一个高性能的Web服务器并且也是一个高性能反向代理服务器,多种测试结果表面Nginx在处理静态文件的速度以及性能要优于Apache,而在一些项目中我们可能需要使用Apache搭配nginx做反代,以获得良好的性能提升

今天本教程主要讲如何使用nginx做反向代理服务器.

最基本要求是你的服务器已经安装了Apache作为web,并且运行于80端口.首先我们修改apache默认端口号:

vim /etc/apache2/ports.conf

找到下面行:

NameVirtualHost *:80
Listen 80

我们修改为:

NameVirtualHost *:8080
Listen 8080

修改后我们虚拟主机或默认主机配置文件也要相应修改一下:

#这里默认端口80咱改为8080

现在我们接着禁用一些不需要的模块:

vim /etc/apache2/apache2.conf
KeepAlive Off

接着继续使用命令禁用下列模块:

a2dismod deflate
a2dismod cgi
a2dismod autoindex
a2dismod negotiation
a2dismod ssl

接着我么安装一个转发模块:

apt-get install libapache2-mod-rpaf
#此模块作用是将访客真实ip转发给后面应用层的apache,不然web无法货取到真实访客ip

安装好后我们重启apache:

/etc/init.d/apache2 restart

然后接着设置nginx你用apache想必一定没安装nginx,现在我们先安装一下.

apt-get install nginx
rm -rf /etc/nginx/sites-enabled/*
#然后我们要删掉默认的web项目站点,这里主要是防止产生冲突

删除后我们新建一个默认web主机

cat >/etc/nginx/sites-available/000-default <

并且修改或新建一个项目使请求转发到后面 apachecat >/etc/nginx/sites-available/youdomain.com < 然后我们重启 nginx/etc/init.d/nginx restart #service nginx restart 发起一个请求看看,若后端出现无法获取真实ip问题,记得检查下前面我们提到的转发模块是否安装加载正常.若没问题,恭喜你,配置成功啦.

Kafka、Logstash、Nginx日志收集入门

Nginx作为网站的第一入口,其日志记录了除用户相关的信息之外,还记录了整个网站系统的性能,对其进行性能排查是优化网站性能的一大关键。
Logstash是一个接收,处理,转发日志的工具。支持系统日志,webserver日志,错误日志,应用日志,总之包括所有可以抛出来的日志类型。一般情景下,Logstash用来和ElasticSearch和Kibana搭配使用,简称ELK,本站http://www.wenzhihuai.com除了用作ELK,还配合了Kafka进行使用。
kafka是一个分布式的基于push-subscribe的消息系统,它具备快速、可扩展、可持久化的特点。它现在是Apache旗下的一个开源系统,作为hadoop生态系统的一部分,被各种商业公司广泛应用。它的最大的特性就是可以实时的处理大量数据以满足各种需求场景:比如基于hadoop的批处理系统、低延迟的实时系统、storm/spark流式处理引擎。

下面是本站日志系统的搭建

一、Nginx日志

为了配合ELK的使用,把日志变成json的格式,方便ElasticSearch对其检索。

    log_format main ''{"@timestamp":"$time_iso8601",''
      ''"host": "$server_addr",''
      ''"clientip": "$remote_addr",''
      ''"size": $body_bytes_sent,''
      ''"responsetime": $request_time,''
      ''"upstreamtime": "$upstream_response_time",''
      ''"upstreamhost": "$upstream_addr",''
      ''"http_host": "$host",''
      ''"url": "$uri",''
      ''"xff": "$http_x_forwarded_for",''
      ''"referer": "$http_referer",''
      ''"agent": "$http_user_agent",''
      ''"status": "$status"}'';
    access_log  logs/access.log  main;

然后执行nginx -t检验配置,nginx -s reload重启nginx即可。
注意:

  1. 这里的单引号用来标识不换行使用的,如果没有的话,Logstash会每一行都发送一次。

  2. 格式一定一定要规范。

二、Logstash

下载安装的具体请看Logstash官网,这里只讲讲如何配置,

输入

input {
    file {
        type => "nginx_access"
        path => "/usr/share/nginx/logs/access.log"
        codec => "json"
    }
}

过滤

filter,由于本站没有涉及到很复杂的手机,所以不填

输出

output {
stdout{
codec => rubydebug
}
kafka {
bootstrap_servers => “119.29.188.224:9092” #生产者
topic_id => “nginx-access-log” #设置写入kafka的topic
    # compression_type => "snappy"    #消息压缩模式,默认是none,可选gzip、snappy。
    codec => json       #一定要加上这段,不然传输错误,${message}
}
elasticsearch {
    hosts => "119.29.188.224:9200"    #Elasticsearch 地址,多个地址以逗号分隔。
    index => "logstash-%{type}-%{+YYYY.MM.dd}"    #索引命名方式,不支持大写字母(Logstash除外)
    document_type => "%{type}"    #文档类型
}
}

具体字段:

stdout:控制台输出,方便tail -f查看,可不要

kafka:输出到kafka,bootstrap_servers指的是kafka的地址和端口,topic_id是每条发布到kafka集群的消息属于的类别,其中codec一定要设置为json,要不然生产者出错,导致消费者是看到${message}。
elasticsearch:输出到elasticsearch,hosts指的是elasticsearch的地址和端口,index指的命名方式
然后启动Logstash:

nohup bin/logstash -f config/nginxlog2es.conf –path.data=tmp &

tail -f 查看nohup

未分类

三、kafka

目前的云服务器都用了NAT转换公网,如果不开启外网,kafka会默认使用内网私有地址访问,所以要开启外网访问
只需要在config/server.properties里加入:

advertised.host.name=119.29.188.224

改变默认端口:

advertised.host.port=9200

启动步骤:

(1)ZooKeeper启动

bin/zookeeper-server-start.sh config/zookeeper.properties

(2)启动Kafka

nohup bin/kafka-server-start.sh config/server.properties &

(3)创建一个topic

bin/kafka-topics.sh –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic test

查看topic数量

bin/kafka-topics.sh –list –zookeeper localhost:2181

(4)生产者发送消息

bin/kafka-console-producer.sh –broker-list localhost:9092 –topic test

(5)消费者接收消息

bin/kafka-console-consumer.sh –bootstrap-server localhost:9092 –topic test –from-beginning

删除

删除kafka存储的日志,在kafka的config/server.properties的log.dirs=/tmp/kafka-logs查看

四、Spring Boot与Kafka

多模块的Spring Boot与Kafka

(1)在父pom.xml中添加:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-releasetrain</artifactId>
            <version>Fowler-SR2</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.5.9.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

(2)在消费者模块中添加:

    <parent>
        <artifactId>micro-service</artifactId>
        <groupId>micro-service</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

配置文件:

# 本地运行端口
server.port=8082
# kafka地址和端口
spring.kafka.bootstrap-servers=119.29.188.224:9092
# 指定默认消费者group id
spring.kafka.consumer.group-id=myGroup
# 指定默认topic id
spring.kafka.template.default-topic=nginx-access-log
# 指定listener 容器中的线程数,用于提高并发量
spring.kafka.listener.concurrency=3
# 偏移量,最好使用latest,earily会从kafka运行起开始一直发送
spring.kafka.consumer.auto-offset-reset=latest
# 心跳检测
spring.kafka.consumer.heartbeat-interval=100

(5)接收消息

@Component
public class MsgConsumer {
    @KafkaListener(topics = {"nginx-access-log"})
    public void processMessage(String content) {
        System.out.println(content);
    }
}

(6)测试

运行之后点击网站http://www.wenzhihuai.com可看到:

未分类

完整代码可以到https://github.com/Zephery/micro-service查看

错误记录

(1)与Spring的包冲突:

Error starting ApplicationContext. To display the auto-configuration report re-run your application with ''debug'' enabled.
2018-01-05 11:10:47.947 ERROR 251848 --- [           main] o.s.boot.SpringApplication               : Application startup failed
org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) ~[spring-context-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]

解决办法:去掉父pom.xml文件里所有关于spring的包,只保留spring boot的即可

(2)消费者只接受到${message}消息

未分类

解决办法:

一定要在output的kafka中添加

codec => json

Linux下Nginx+Tomcat整合与配置

安装JDK

下载的jdk文件为:jdk-6u45-linux-x64.bin,执行如下命令进行安装:

#./jdk-6u12-linux-i586.bin

安装tomcat

#tar zxvf apache-tomcat-6.0.18.tar.gz
#mv apache-tomcat-6.0.29 tomcat

这里我将解压后的apache-tomcat-6.0.29重命名为了tomcat方便操作。

配置环境变量

编辑/etc下的profile文件,加上如下内容:

JAVA_HOME="/opt/app/jdk1.6.0_45"
CLASS_PATH="$JAVA_HOME/lib:$JAVA_HOME/jre/lib"
PATH=".:$PATH:$JAVA_HOME/bin"
CATALINA_HOME="/opt/app/tomcat"
export JAVA_HOME CATALINA_HOME

执行下面命令使变更生效:

# source /etc/profile

启动tomcat并输入http://domain:8080,如果看到猫的页面即tomcat和jdk安装成功

新建文件目录/home/www为网站存放目录,设置server.xml文件,在Host name=”localhost”处将appBase=的指向路径改为/home/www/web

创建index.jsp至/home/www/web/ROOT,内容为:“hello!” 重新启动tomcat,重新访问,如果看到index.jsp文件内容hello!表示设置成功。

安装Nginx

执行如下命令解压nginx:

# tar zxvf nginx-1.4.4.tar.gz
# mv nginx-1.4.4 nginx

同样重命名了一下。

安装nginx:

# ./configure --prefix=/opt/app/nginx

结果出现了错误:error: C compiler cc is not found,按网上所说安装编译源码所需的工具和库:

#yum install gcc gcc-c++ ncurses-devel perl

再次安装,发现还有错误:the HTTP rewrite module requires the PCRE library.

执行

# yum -y install pcre-devel openssl openssl-devel

终于成功,

# ./configure --prefix=/opt/app/nginx
# make
# make install

nginx安装成功后的安装目录为/opt/app/nginx

在conf文件夹中新建proxy.conf,用于配置一些代理参数,内容如下:

#!nginx (-) 
# proxy.conf 
proxy_redirect          off;
proxy_set_header        Host $host;
proxy_set_header        X-Real-IP $remote_addr;  #获取真实ip
#proxy_set_header       X-Forwarded-For   $proxy_add_x_forwarded_for; #获取代理者的真实ip
client_max_body_size    10m;
client_body_buffer_size 128k;
proxy_connect_timeout   90;
proxy_send_timeout      90;
proxy_read_timeout      90;
proxy_buffer_size       4k;
proxy_buffers           4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;

编辑安装目录下conf文件夹中的nginx.conf,输入如下内容

#运行nginx所在的用户名和用户组
#user  www www; 
#启动进程数
worker_processes 8;
#全局错误日志及PID文件
error_log  /opt/app/nginx/logs/nginx_error.log  crit;
pid        /opt/app/nginx/nginx.pid;
#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 65535;
#工作模式及连接数上限
events
{
  use epoll;
  worker_connections 65535;
}
#设定http服务器,利用它的反向代理功能提供负载均衡支持
http
{
  #设定mime类型
  include       mime.types;
  default_type  application/octet-stream;
  include /opt/app/nginx/conf/proxy.conf;
  #charset  gb2312;
  #设定请求缓冲    
  server_names_hash_bucket_size 128;
  client_header_buffer_size 32k;
  large_client_header_buffers 4 32k;
#  client_max_body_size 8m;
  sendfile on;
  tcp_nopush     on;
  keepalive_timeout 60;
  tcp_nodelay on;
#  fastcgi_connect_timeout 300;
#  fastcgi_send_timeout 300;
#  fastcgi_read_timeout 300;
#  fastcgi_buffer_size 64k;
#  fastcgi_buffers 4 64k;
#  fastcgi_busy_buffers_size 128k;
#  fastcgi_temp_file_write_size 128k;
#  gzip on;
#  gzip_min_length  1k;
#  gzip_buffers     4 16k;
#  gzip_http_version 1.0;
#  gzip_comp_level 2;
#  gzip_types       text/plain application/x-javascript text/css application/xml;
#  gzip_vary on;
#limit_zone  crawler  $binary_remote_addr  10m;
###禁止通过ip访问站点
 # server{
#        server_name _;
 #       return 404;
 #       }
  server
  {
    listen       80;
    server_name  localhost;
    index index.html index.jsp;
    root  /opt/www/static;
    #limit_conn   crawler  20;    
    location ~ .*.(jsp|shtml)$ #所有shtml的页面均交由tomcat处理
    {
      index index.jsp;
      proxy_pass http://localhost:8080;#转向tomcat处理
      }
    location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ #设定访问静态文件直接读取不经过tomcat
    {
      expires      30d;
    }
    location ~ .*.(js|css)?$
    {
      expires      1h;
    }    
   }  
#定义访问日志的写入格式
     log_format  access  '$remote_addr - $remote_user [$time_local] "$request" '
              '$status $body_bytes_sent "$http_referer" '
              '"$http_user_agent" $http_x_forwarded_for';
    access_log  /opt/app/nginx/logs/localhost.log access;#设定访问日志的存放路径   
}

修改/usr/local/nginx/conf/nginx.conf配置文件后,请执行以下命令检查配置文件是否正确:

#/opt/app/nginx/sbin/nginx -t

如果出现下面两行,说明正确:

the configuration file /opt/app/nginx/conf/nginx.conf syntax is ok
the configuration file /opt/app/nginx/conf/nginx.conf was tested successfully

如果提示unknown host,则可在服务器上执行:ping www.baidu.com如果也是同样提示unknown host则有两种可能:

a、服务器没有设置DNS服务器地址,查看/etc/resolv.conf下是否设置,若无则加上

b、防火墙拦截

启动nginx的命令

#/opt/app/nginx/sbin/nginx

这时,输入以下命令查看Nginx主进程号:

ps -ef | grep "nginx: master process" | grep -v "grep" | awk -F ' ' '{print $2}'

停止nginx的命令

#/opt/app/nginx/sbin/nginx -s stop

在不停止Nginx服务的情况下平滑变更Nginx配置

输入以下命令查看Nginx主进程号:

ps -ef | grep "nginx: master process" | grep -v "grep" | awk -F ' ' '{print $2}'

屏幕显示的即为Nginx主进程号,例如:

6302

这时,执行以下命令即可使修改过的Nginx配置文件生效:

kill -HUP 6302

或者无需这么麻烦,找到Nginx的Pid文件:

kill -HUP `cat /usr/local/nginx/nginx.pid`

nginx如何配置兼容ThinkPHP各种url模式

我们知道ThinkPHP是有多种访问模式的,比如较常用的普通模式以及rewrite模式,也就是网址 /index.php?m=Zhonglian&c=Index&a=register 以及 网址 /DailiUser/alipay_notify_url,这两种模式用得比较多了。

为什么要做多种兼容呢,因为最近做了支付宝的回调,而支付宝是不认第一种模式的,只能使用 rewrite 模式,而我本地使用的是 nginx 服务器,所以需要在 nginx里面去做一下兼容配置了,配置的方法也很简单,在linux或者windows+nginx的环境下配置 nginx.conf 文件。

location / {    
     root /var/www;    
     index index.html index.htm index.php;    
     if (!-e $request_filename) {    
         rewrite ^/index.php(.*)$ /index.php?s=$1 last;    
         rewrite ^(.*)$ /index.php?s=$1 last;    
         break;    
     }    
 }    

好了,配置成功之后,Thinkphp的三种模式都可以兼容使用了,在本地的话就可以使用普通的模式,如果使用支付宝或者微信支付等回调的话就可以使用 rewrite 类的模式。

nginx限速之连接数限制技巧分享

前言

我们经常会遇到这种情况,服务器流量异常,负载过大等等。对于大流量恶意的攻击访问,会带来带宽的浪费,服务器压力,影响业务,往往考虑对同一个ip的连接数,并发数进行限制。nginx 内置模块限速怎么使用就不多说了,今天来说说连接数和单个连接数限速的事。话不多说了,来一起看看详细的介绍吧。

场景

A公司有100人,A公司只有一个公网IP,假设A公司可能有100个人同时在下载你的网站文件。

但是,你的连接数限制配置为:

limit_conn_zone $binary_remote_addr zone=perip:1m;
server {
 ---
 limit_conn perip 1;
 limit_rate 1024k;
 ---
}

允许单个连接数,单个连接数最大带宽为1M。
这样就会有99个人的请求状态为 503, 其他人如果想下载就必须人工等待(nginx不会通知用户说A用户下载完了,该你B用户下载了)。这样造成的用户体验极差。但是优点也很明显,带宽很快就会降下来。

可能有人就要问了,你限制成很低的连接数是想搞事情?NO,绝对不是。前面的100个人同时下载网站资源的情况有多大呢?没做过统计,但是可能性极小。并且前端页面和下载资源不共用一个域名,所以不会影响到前端页面的访问。
那都是谁在大量使用连接数呢?分两类:

  • 下载工具类(迅雷)。
  • 各种各样的采集程序。
  • 同时进行多个下载任务。

小明快乐的在看电视,瞥了左边频幕一眼,握草,带宽又满了,来吧,限速吧,

limit_conn_zone $binary_remote_addr zone=perip:1m;
server {
 ---
 limit_rate 1024k;
 ---
}

小明做了如上限速,OK,我告诉你们谁被限速了,当然是浏览器下载用户,360浏览器的下载器都不一定能限制,好的,来算算速度吧。
浏览器: 2014K
下载器: 1024 * 15(最大连接数) * VIP
采集器: 1024 * 连接数

所以我们得到如下结论:

带宽有限,同个IP同时下载的情况很小的,或者说是可以预知的业务,尽量将连接数限制的小一点。
反之,别限制了。就降低单个连接数带宽吧!要知道大家谁没事会用浏览器自带下载器下载呢?
注:本文只探讨nginx限速模块在不同业务下的限速

彩蛋:偶尔发现,将连接数限制为1迅雷不能高速下载了。

未分类

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对编程小技巧的支持。

Nginx下修改WordPress固定链接设置后无法访问

用WordPress肯定是要用固定链接,不仅目录清晰,而且利于SEO。当你用Apache做Web服务器的时候自然是没什么问题,只需要在设置-固定链接设置中选择一下就好了,不过当你用Nginx的时候,就有点小问题了,当你选固定链接的时候,你的网站会无法访问。

未分类

以下文章主要介绍了Nginx下修改WordPress固定链接导致无法访问的问题解决,同时作者也给出了官方关于修改固定链接的方法,需要的朋友可以参考下:

wordpress提供多种类型的链接形式

未分类

我选择了自定义。下面就出现了修改固定链接后,访问文章会出现404错误,以前我用apache做web服务器,所以只要apache下就三个关键,即

wordpress对目录下的.htaccess拥有读写权限

固定链接的目录结构需要 Apache服务器的mod_rewrite模块支持,所以在Apache配置文件httpd.conf中将 LoadModule rewrite_module modules/mod_rewrite.so设置为启用。

同样是Apache配置文件,其中对于站点目录下的AllowOverride None的参数设置为All。当然修改完配置后,一定要重启Apache服务。

由于是新配置的本地测试环境,2、3两项问题同时出现,逐项更正设置后,固定链接的工作正常。

现在我用的nginix,所以也要修改nginix的ngnix.conf配置文件,让其支持重定向。

假设我的wordpress博客是的 server{}段是直接放到放到了nginx.conf (有的人为了方便管理,都习惯在单独写个vhost/目录来存放每个网站的配置文件,这就要根据你自己的设置来添加了)

vi /your_nginx_path/conf/nginx.conf

按照nginix的正则表达式的规则,可参考:Nginx 的中文维基

  • ^:匹配输入字符的开始位置

  • $:匹配数日字符串的结束位置

  • +:匹配前面的子表达式一次或者多次

  • [0-9]:数字字符范围

  • $1:调用变量

在server{} 字段 中的 “root /websit/wwwroot/;”(这行就是指定网站所在目录的) 这一行的下面 ,添加下面的内容:

if (-f $request_filename/index.html){
rewrite (.*) $1/index.html break;
}
if (-f $request_filename/index.php){
rewrite (.*) $1/index.php;
}
if (!-f $request_filename){
rewrite (.*) /index.php;
}
rewrite /wp-admin$ $scheme://$host$uri/ permanent;//这行是为了防止打开后台、插件页等打不开的。

保存后,输入 /etc/init.d/nginx restart , 重启nginix。就ok了!

相当于告诉nginix访问这些后按照正则表达式转到其唯一正确的地址,以此打开文章。

貌似/%postname%/会以中文为链接,为了seo,可以考虑一个插件 WP Slug Translate,它会自动换中文标题为英文,不能联网就改为拼音。

貌似官方给出了新的pha100 pha-3,也简单的多。这里假设,我在nginx的conf文件夹下创建个wordpress.conf ,将下面的代码粘贴进去:

location / {
try_files $uri $uri/ /index.php?$args;
}
rewrite /wp-admin$ $scheme://$host$uri/ permanent;

我的博客nginx虚拟机配置文件在 conf/vhost/www.dabu.info.conf 。同样,在root 那行下面,添加一行:

include wordpress.conf;

接着重启nginx就可以正常访问了。

Nginx如何解决“The plain HTTP request was sent to HTTPS port”错误

Nginx HTTP服务器的一条报错“400 Bad Request: The plain HTTP request was sent to HTTPS port”,本文将讲解如何解决这个问题。从报错的字面意思上来看,是因为HTTP请求被发送到HTTPS端口,这种报错多出现在Nginx既处理HTTP请求又处理HTTPS请求的情况。

为了便于理解,我们假设这样一个场景。Nginx为web网站提供提供服务,而其中只有一个网站使用SSL协议。

以下是Nginx常用的SSL配置(出于安全原因,我们使用了示例域名),配置文件将让Nginx侦听80和443端口,并将所有的HTTP请求重定向到HTTPS。

server{
        listen 80;
        server_name example.com www.example.com;
        return 301 https://www.example.com$request_uri;
}
server {
        listen 443 ssl http2;
        server_name example.com www.example.com;

        root   /var/www/html/example.com/;
        index index.php index.html index.htm;

        #charset koi8-r;
        access_log /var/log/nginx/example.com/example.com_access_log;
        error_log   /var/log/nginx/example.com/example.com_error_log   error;

        # SSL/TLS configs
        ssl on;
        ssl_certificate /etc/ssl/certs/example_com_cert_chain.crt;
        ssl_certificate_key /etc/ssl/private/example_com.key;

        include /etc/nginx/ssl.d/ssl.conf;

        location / {
                try_files $uri $uri/ /index.php?$query_string;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
                root   /var/www/html/example.com/;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ .php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ .php$ {

                root   /var/www/html/example.com/;
                fastcgi_pass   127.0.0.1:9001;
                #fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                include         fastcgi_params;
                include /etc/nginx/fastcgi_params;

        }
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /.ht {
        #    deny  all;
        #}
}

以上的配置看上去都很正常,但是用户想通过80端口来访问网站时,例如使用http://example.com,那么这个用户就会在浏览器收到错误400“The plain HTTP request was sent to HTTPS port”,示例图片如下:

未分类

出现这个错误,因为每一次客户试图通过HTTP访问你的网站,这个请求被重定向到HTTPS。于是Nginx预计使用SSL交互,但原来的请求(通过端口80接收)是普通的HTTP请求,于是会产生错误。

另一方面,如果一个客户使用https://example.com访问网站,他们就不会遇到上述错误。此外,如果你有其他的网站配置为不使用SSL,Nginx会尝试使用HTTPS,这种情况下也会造成上述错误。

解决办法也很简单,就是将上面配置文中的“ ssl on ; ” 注释掉或者修改成 “ ssl off ;”,这样,Nginx就可以同时处理HTTP请求和HTTPS请求了。

Nginx手动安装、增加ssl模块、升级更新、删除等操作

以下的操作都在Ubuntu系统下,其它系统请绕过

一般我们都需要先装pcre, zlib,前者为了重写rewrite,后者为了gzip压缩。

sudo apt-get install libpcre3 libpcre3-dev        //PCRE库
sudo apt-get install zlib1g-dev                        //zlib库
sudo apt-get install openssl libssl-dev            //OpenSSL库

1. 选定源码目录

选定目录 /usr/local/

cd /usr/local/

2. 安装nginx

Nginx 一般有两个版本,分别是稳定版和开发版,您可以根据您的目的来选择这两个版本的其中一个,下面是把 Nginx 安装到 /usr/local/nginx 目录下的详细步骤:
备注:nginx请到http://nginx.org/download 查找并下载。

cd /usr/local/
wget http://nginx.org/download/nginx-1.2.8.tar.gz
tar -zxvf nginx-1.2.8.tar.gz
cd nginx-1.2.8  
./configure --prefix=/usr/local/nginx 
make
make install

–with-pcre=/usr/src/pcre-8.21 指的是pcre-8.21 的源码路径。
–with-zlib=/usr/src/zlib-1.2.7 指的是zlib-1.2.7 的源码路径。

3. 启动

确保系统的 80 端口没被其他程序占用,

/usr/local/nginx/sbin/nginx

检查是否启动成功:

netstat -ano|grep 80 有结果输入说明启动成功
打开浏览器访问此机器的 IP,如果浏览器出现 Welcome to nginx! 则表示 Nginx 已经安装并运行成功。

4. 重启

/usr/local/nginx/sbin/nginx –s reload

5. 修改配置文件

cd /usr/local/nginx/conf
vi nginx.conf

6. 增加未开启的ssl,http2模块

切换到源码包cd /usr/local/nginx-1.2.8后查看nginx原有的模块

sudo /usr/local/nginx/sbin/nginx -V 

原有应该如下:

--prefix=/usr/local/nginx 

新的配置应该这么写:

--prefix=/usr/local/nginx --with-http_ssl_module --with-http_v2_module 

那么应该运行下面的命令,配置完成后,执行:

./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_v2_module 

配置完成后,运行命令:

make 

不要make install,否则就覆盖安装了。

先停止nginx运行pkill -9 nginx,这里强制停止。

然后备份原有已经安装好的nginx配置

cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak 

将刚刚编译的覆盖原有的nginx

cp ./objs/nginx /usr/local/nginx/sbin/ 

启动nginx:

/usr/local/nginx/sbin/nginx 

查看是否安装成功新的ssl模块:

sudo /usr/local/nginx/sbin/nginx -V

7. 升级nginx

下载最新版nginx源码并解压编译

cd /usr/local/
wget http://nginx.org/download/nginx-1.13.6.tar.gz
tar zxvf nginx-1.13.6.tar.gz
cd nginx-1.13.6
#编译nginx,添加http_v2模块应用

开始编译nginx

./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_v2_module 

编译完成后,执行make,但不执行make install

make 

将旧版本的nginx二进制文件,重命名一个名字,在这期间,当前运行的nginx进程不会停止,不影响应用运行。

mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.old 

然后将上一步通过make编译好的新版nginx二进制文件,拷贝到运行目录

cp ./objs/nginx /usr/local/nginx/sbin/nginx 

在源码目录根目录下,执行更新安装命令:

make upgrade 

注意:如果原来的相关配置文件中,写有和ssl有关的配置信息,需要先暂时注释掉,否则更新时会报错。

更新完成后,执行

nginx -V 

可以看到nginx已经更新到1.13.6版本。

NGINX下升级HTTPS踩到的坑

由于项目业务升级,全站升级https协议。

导致了资源跨域 https下无法访问http协议的资源,项目原本有很多图片存储在数据库url使用http协议,导致了项目的图片,样式丢失,部分图片上传组件也无法使用。

HTTPS 是 HTTP over Secure Socket Layer,以安全为目标的 HTTP 通道,所以在 HTTPS 承载的页面上不允许出现 http 请求,一旦出现就是提示或报错:

Mixed Content: The page at 'https://www.example.com' was loaded over HTTPS, but requested an insecure image ‘http://static.example.com/test.jpg’. This content should also be served over HTTPS.

首先,为了解决样式问题,我在前端页面,引入了一个meta

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />

等效于用PHP设置头部

header("Content-Security-Policy: upgrade-insecure-requests");

这样导致了一个问题,我的测试环境下并没有ssl证书,因此又冒出很多问题。

后面接触了下CSPCSP

我改变了下思路,在nginx上做处理。一个nginx的配置

server {
        listen       443;
        server_name  www.example.com;
        #charset koi8-r;

        error_log  /logs/nginx/error.log;
        root /var/www/www.example.com;
        index  index.php index.html index.htm;
        ssl on;
        ssl_certificate   cert/test/test.pem;
        ssl_certificate_key  cert/test/test.key;
        ssl_session_timeout 5m;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;

        add_header  X-Frame-Options  deny;
        add_header  X-Content-Type-Options  nosniff;
        add_header  X-XSS-Protection "1; mode=block";
        add_header Strict-Transport-Security max-age=86400;
        add_header Content-Security-Policy "upgrade-insecure-requests;default-src *;script-src 'self' https://static.example.com http://static.example.com 'unsafe-inline' 'unsafe-eval';style-src https://static.example.com http://static.example.com 'self' 'unsafe-inline';frame-src 'self';connect-src 'self';img-src https://static.example.com http://static.example.com data: blob: 'self'";

        location / {
                if (!-f $request_filename){
                        rewrite ^/(.*)$ /index.php?s=$1 last;
                        break;
                }
                limit_except GET POST DELETE PUT {
                        deny all;
                }
        }


        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
                        root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ .php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ .php$ {
                        fastcgi_pass   127.0.0.1:9000;
                        fastcgi_index  index.php;
                        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                        include        fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        location ~ /.ht {
                        deny  all;
        }
}

几个header的意思,改天再写一篇文章详细讲解下。