Linux安装nginx服务

109 阅读1分钟

1、下载nginx

https://nginx.org/en/download.html

2、安装依赖包

yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel

3、卸载旧Nginx Module

yum remove nginx-mod* -y

4、创建运行用户

useradd -s /sbin/nologin -d /var/lib/nginx nginx

5、解压安装包

tar -xzvf nginx-1.24.0.tar.gz

6、编译和安装

cd nginx-1.24.0
./configure --prefix=/usr/local/nginx --with-http_ssl_module
make
make install

7、修改配置文件

vi /etc/nginx/nginx.conf

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /usr/local/nginx/conf/mime.types;
    default_type        application/octet-stream;

    server {
        listen       8081;  # 需要修改
        server_name  localhost;

    location / {
    root  /opt/test; # 需要修改
    index index.html index.htm;
    try_files $uri $uri/ /index.html;
    }

    location /portals {
            proxy_pass http://177.6.218.3:8082;  # 需要修改
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Host $http_host;
            proxy_set_header X-forwarded-for $remote_addr;
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

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

8、创建启动脚本

vi /etc/systemd/system/nginx.service

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

[Unit]
Description=nginx service
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

9、添加权限

chmod 755 /etc/systemd/system/nginx.service

10、启动和停止

systemctl daemon-reload
systemctl enable nginx
systemctl start nginx # nginx启动
systemctl stop nginx # nginx停止