nginx安装及使用

Nginx (engine x) 是一个高性能web服务器和反向代理服务器。

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

安装

# 在Debian10上安装nginx
apt install nginx

# 查看版本
nginx -v
# nginx version: nginx/1.14.2

# 启动 /usr/sbin/nginx
nginx

# 指定配置文件启动
nginx -c /etc/nginx/nginx.conf

# 查看进程
ps aux | grep nginx

# 查看状态
systemctl status nginx

# 重启nginx
systemctl restart nginx

# 停止
nginx -s stop

启动后可以用浏览器访问http://127.0.0.1或服务器IP地址,展示默认的Welcome to nginx!页面。

配置

默认配置文件路径: /etc/nginx/nginx.conf

Nginx作为Web服务器

1.创建网站内容

创建简单的HTML文件index.html,放在/var/www/html目录下

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>My Static Website</title>
</head>
<body>
    <h1>Welcome to my website!</h1>
    <p>This is a static website hosted by Nginx.</p>
</body>
</html>

2.配置Nginx服务

修改Nginx的配置文件vi /etc/nginx/nginx.conf

http {

    server {
        listen 80;
        server_name example.com;

        location / {
            root /var/www/html;
            index index.html;
        }
    }
    # Other configurations here
}

重启nginx systemctl restart nginx,浏览器重新访问服务器的IP地址即可看到网页内容。

Nginx作为反向代理服务器

http {
    # 应用服务器
    upstream  app_service {
        #ip_hash; 
        server   192.168.10.100:8080 max_fails=2 fail_timeout=30s ;  
        server   192.168.10.101:8080 max_fails=2 fail_timeout=30s ;  
    }
    # 代理访问地址: localhost:80
    server {
        listen       80;
        server_name  localhost;
        location / {
            proxy_pass http://app_service;
        }
    }
    # Other configurations here
}

请求到localhost:80地址的消息将会转发到app_service中配置的后端服务器集群上。

如果未转发到后端服务器上,先检查下默认的配置有没有注释掉,比如

#include /etc/nginx/conf.d/*.conf;
#include /etc/nginx/sites-enabled/*;
posted @ 2023-05-15 20:43  rustling  阅读(25)  评论(0编辑  收藏  举报