nginx学习

168 阅读2分钟

nginx源码安装

进入官网查找需要下载的链接地址(我这里用的是1.16.1)

wget http://nginx.org/download/nginx-1.16.1.tar.gz

创建一个文件夹用来放置资源包

mkdir -p nginx/core
mv nginx-1.16.1.tar.gz nginx/core

进入nginx资源包目录进行解压缩

cd nginx/core
tar -xzf nginx-1.16.1.tar.gz

进入资源文件中,发现configure

.configure

编译

make

安装

make install

Nginx命令

使用上述安装,nginx默认安装路径为

/usr/local/nginx

使用源码安装,执行nginx命令需要到sbin目录下

cd /usr/local/nignx/sbin

启动命令

nginx

优雅关闭nginx命令

nginx -s quit

粗暴关闭nginx命令

nginx -s stop

检查配置文件语法是否错误

nginx -t

不中断服务重载nginx配置

nginx -s reload

nginx配置文件

nginx配置文件在nginx目录下的conf/nginx.conf 以下是一个配置文件示例

worker_processes  2;
worker_cpu_affinity 01 10;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    # 配置日志格式
    log_format combined_with_host  '$remote_addr - $remote_user [$time_local] "$request" '
                          '$status $body_bytes_sent "$http_referer" '
                          '"$http_user_agent" "$http_x_forwarded_for"';

    # 配置访问日志和错误日志
    access_log /usr/local/nginx/logs/access.log combined_with_host;
    error_log /usr/local/nginx/logs/error.log warn;

    server {
        listen       443 ssl;  # 监听 443 端口
        server_name  localhost;  # 绑定到指定 IP 地址
        ssl_certificate /usr/local/nginx/ssl/nginx-selfsigned.crt;
       ssl_certificate_key   /usr/local/nginx/ssl/nginx-selfsigned.key;
        # 处理 所有请求,代理到目标服务器
        location / {
            if ($request_method = 'OPTIONS') {
                add_header Access-Control-Allow-Origin 'http://localhost:8080';
                add_header Access-Control-Allow-Headers '*';
                add_header Access-Control-Allow-Methods '*';
                add_header Access-Control-Allow-Credentials 'true';
                return 204;
            }
            if ($request_method != 'OPTIONS') {
                add_header Access-Control-Allow-Origin 'http://localhost:8080' always;
                add_header Access-Control-Allow-Credentials 'true';
                add_header Access-Control-Allow-Headers '*';
                add_header Access-Control-Allow-Methods '*';
            }
            proxy_pass http://localhost:8081;  # 目标服务器   
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }

        # 其他请求返回 404
        location /NOTF {
            return 404;
        }
    }
}

nginx配置openssl

查看服务器openssl版本

openssl version

nginx 增加ssl模块(需要进入源码目录我这里是/root/nginx/core/nginx-1.16.1)

cd /root/nginx/core/nginx-1.16.1
./configure --with-http_ssl_module

编译

make

新编译的 Nginx 二进制文件**(包含 SSL 模块)覆盖替换旧的可执行文件

sudo cp root/nginx/core/nginx-1.16.1/objs/nginx /usr/local/nginx/sbin/nginx

重新加载nginx(需要在安装目录下的sbin目录下)

nginx -s reload

查看nginx是否有ssl模块(V是大写)

nginx -V