标签: 反向代理

  • Linux – Nginx的安装与配置

    Linux – Nginx的安装与配置

    系统软件源直接安装

    使用命令一键安装

    Centos:

    yum install nginx -y

    Ubuntu:

    apt update
    apt install -y nginx

    nginx配置文件默认保存在 /etc/nginx

    其中 conf.d 的子文件夹中会有一个默认战队

    默认站点在 /var/www/html/,可以直接将网页存放至该目录后访问IP即可

    编译安装

    环境准备

    [postsbox post_id=7]

    获取nginx源码

    下载并解压下载的源码包

    wget https://nginx.org/download/nginx-1.28.0.tar.gz
    tar -zxf nginx-1.28.0.tar.gz

    这里下载的是nginx发行版1.28.0

    如需获取最新的nginx发行版本通过 Nginx官方下载页面 进行下载

    编译安装

    切换到解压的目录,开始进行安装

    默认参数安装:

    ./configure
    make
    make install

    命令解释:

    ./configure 为编译前检查,如果环境安装错误,则会报错,后续无法执行make进行编译

    make 编译源码获取运行文件与配置文件等

    make install 将编译后的结果安装至系统

    也可以一键运行,在没有报错时,会依次执行该3个命令

    直接运行 make install 也会直接编译,并安装

    ./configure && make install

    默认会将nginx安装至 /usr/local/nginx 的目录下

    默认不带参数安装不带ssl模块,这会导致无法开启https

    要开启https需要添加ssl参数

    ./configure \
    --user=nginx \
    --group=nginx \
    --with-http_ssl_module \
    --prefix=/usr/local/nginx \
    --conf-path=/etc/nginx/nginx.conf \
    --sbin-path=/usr/sbin/nginx \
    --error-log-path=/var/log/nginx/nginx_error.log \
    --http-log-path=/var/log/nginx/nginx_access.log \
    --pid-path=/usr/local/nginx/run/nginx.pid \
    --with-http_image_filter_module \
    --with-pcre \
    && make && make install

    编译参数说明

    参数名称 意义
    --user=nginx 指定启动用户
    --group=nginx 指定启动用户组
    --prefix=/usr/local/nginx 指定安装目录
    --conf-path=/etc/nginx/nginx.conf 指定配置文件路径
    --sbin-path=/usr/sbin/nginx 指定nginx的sbin目录,可执行文件的安装路径
    --error-log-path=/var/log/nginx/nginx_error.log 指定nginx错误日志存放路径
    --http-log-path=/var/log/nginx/nginx_access.log 指定nginx访问日志存放路径
    --pid-path=/usr/local/nginx/run/nginx.pid 指定nginx运行时的pid存放路径
    --with-http_image_filter_module 图片过滤处理模块
    --with-pcre pcre模块

    如果指定启动用户,需要创建一个无法登陆用户

    创建nginx用户组

    创建nginx用户并加入用户组,指定不创建home目录且shell设为/sbin/nologin

    groupadd -r nginx
    useradd -r -g nginx -d /var/cache/nginx -s /sbin/nologin -c "nginx user" nginx

    日志的变量

    变量名称 意义
    $remote_addr 用以记录客户端的IP地址
    $http_x_forwarded_for 用以记录客户端的IP地址(可记录代理前的真实IP)
    $remote_user 用来记录客户端用户名称(需HTTP认证)
    $time_local 用来记录访问时间与时区
    $request 用来记录请求的URL与HTTP协议
    $status 用来记录请求状态(如成功是200)
    $body_bytes_sent 记录发送给客户端文件主体内容大小
    $http_referer 用来记录从哪个页面链接访问过来的

    配置文件解析

    参数名称 意义
    user nginx 设置nginx服务的系统使用用户
    worker_processes auto 工作进程数,一般和CPU数保持一致
    error_log /var/log/nginx/error.log 错误日志的保存路径
    pid /run/nginx.pid 存放nginx服务启动时的pid文件路径
    use epoll epoll 是多路复用IO(I/O Multiplexing)中的-一种方式,
    但是仅用于linux2 .6以上内核,可以大大提高nginx 的性能
    events 如1个worker能同时允许多少连接
    include /etc/nginx/default.d/*.conf 加载某个目录下所以的.conf文件

    Server模块下

    参数名称 意义
    listen 80 监听端口(默认为HTTP协议的80端口)
    listen [::]:80 IPv6监听端口(用于支持IPv6协议)
    server_name test.com 域名(可配置多个,用空格分隔)
    root /usr/share/nginx/html 网站根目录(请求文件的查找路径)
    index index.php index.html index.htm 指定首页名称(按顺序查找,用于支持PHP或其他页面类型)

    进阶配置

    开启https(ssl)

    # HTTPS 服务器配置
    server {
        listen 443 ssl http2;
        server_name example.com;  # 替换为你的域名
    
        # SSL证书和私钥路径
        ssl_certificate /path/to/cert.pem;       # 证书文件
        ssl_certificate_key /path/to/key.pem;   # 私钥文件
    
        # SSL会话缓存和超时
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;
    
        # TLS版本和加密套件(推荐配置)
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_prefer_server_ciphers on;
        ssl_ciphers "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384";
    
        # HSTS(HTTP严格传输安全)
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
    
        # 其他安全头
        add_header X-Content-Type-Options nosniff;
        add_header X-Frame-Options "SAMEORIGIN";
        add_header X-XSS-Protection "1; mode=block";
    
        # 网站根目录和默认文件
        root /var/www/html;
        index index.php index.html;
    
        # 其他配置(如PHP解析、反向代理等)
        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }
    }

    目录浏览功能

    在server块中添加

    autoindex on; # 开启目录文件列表
    autoindex_exact_size on; # 显示出文件的确切大小,单位是bytes
    autoindex_localtime on; # 显示的文件时间为文件的服务器时间
    charset utf-8,gbk,gb2312; # 避免中文乱码

    开启PHP

    需要先安装PHP

    [postsbox post_id=9]

    将一下代码添加进server模块中

    一般php-fpm的默认端口是9000

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;  # PHP-FPM监听地址
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

    反向代理

    将代码配置进Server模块中,并将后端地址替换即可

    有其他的特殊地址问题,需要进行特殊处理

    location / {
            proxy_pass http://backend_server;  # 后端服务器地址
            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;
    
            # 可选性能优化参数
            proxy_connect_timeout 30s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
            proxy_buffering on;
            proxy_buffer_size 4k;
            proxy_buffers 4 32k;
            proxy_busy_buffers_size 64k;
        }

    开机自动启动

    编译安装的nginx不会安装成为系统服务,需要手动添加

    添加nginx服务

    vim /usr/lib/systemd/system/nginx.service

    配置文件如下,路径需要改为自己安装的路径:

    [Unit]
    Description=nginx
    After=network.target
    
    [Service]
    Type=forking
    ExecStart=/usr/local/nginx/sbin/nginx
    ExecReload=/usr/local/nginx/sbin/nginx -s reload
    ExecStop=/usr/local/nginx/sbin/nginx -s quit
    PrivateTmp=true
    
    [Install]
    WantedBy=multi-user.target

    保存并重新载入服务

    systemctl daemon-reload

    控制命令:

    systemctl start nginx 开启服务

    systemctl stop nginx 关闭服务

    systemctl status nginx 服务状态

    systemctl restart nginx 重启服务

    systemctl reload nginx 不关闭服务并重新载入配置

    添加开机启动 创建一个脚本文件 vi /etc/init.d/nginx

    #!/bin/bash
    # nginx Startup script for the Nginx HTTP Server
    # it is v.0.0.2 version.
    # chkconfig: - 85 15
    # description: Nginx is a high-performance web and proxy server.
    # It has a lot of features, but it's not for everyone.
    # processname: nginx
    # pidfile: /usr/local/nginx/logs/nginx.pid
    # config: /usr/local/nginx/conf/nginx.conf
    nginxd=/usr/local/nginx/sbin/nginx
    nginx_config=/usr/local/nginx/conf/nginx.conf
    nginx_pid=/usr/local/nginx/logs/nginx.pid
    RETVAL=0
    prog=nginx
    # Source function library.
    . /etc/rc.d/init.d/functions
    # Source networking configuration.
    . /etc/sysconfig/network
    # Check that networking is up.
    [ ${NETWORKING} = no ] && exit 0
    [ -x $nginxd ] || exit 0
    # Start nginx daemons functions.
    start() {
    if [ -e $nginx_pid ];then
    echo nginx already running....
    exit 1
    fi
    echo -n
    <pre wp-pre-tag-1="">
    quot;Starting $prog: 
    daemon $nginxd -c ${nginx_config}
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && touch /var/lock/subsys/nginx
    return $RETVAL
    } # Stop nginx daemons functions.
    stop() {
    echo -n
    <pre wp-pre-tag-1="">
    quot;Stopping $prog: 
    killproc $nginxd
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && rm -f /var/lock/subsys/nginx /usr/local/nginx/logs/nginx.pid
    }
    # reload nginx service functions.
    reload() {
    echo -n
    <pre wp-pre-tag-1="">
    quot;Reloading $prog: 
    #kill -HUP `cat ${nginx_pid}`
    killproc $nginxd -HUP
    RETVAL=$?
    echo
    }
    # See how we were called.
    case $1 in
    start)
    start
    ;;
    stop)
    stop
    ;;
    reload)
    reload
    ;;
    restart)
    stop
    start
    ;;
    status)
    status $prog
    RETVAL=$?
    ;;
    *)
    echo
    <pre wp-pre-tag-1="">
    quot;Usage: $prog {start|stop|restart|reload|status|help}
    exit 1
    esac
    exit $RETVAL

    chmod a+x /etc/init.d/nginx给脚本执行权限

    echo /etc/init.d/nginx start >>/etc/rc.local 添加开机服务

    chmod +x /etc/rc.local 给开机服务添加执行权限