Nginx学习笔记

MirrorYuChen
MirrorYuChen
发布于 2024-11-30 / 18 阅读
0
0

Nginx学习笔记

0.内容概览

1.nginx安装

  • [1] 包管理器
# 1.ubuntu
>> sudo apt update
>> sudo apt install nginx

# 2.mac
>> brew install nginx

# 3.windows
>> scoop install nginx
>> choco install nginx
  • [2] 源码安装
>> sudo apt-get install libpcre3 libpcre3-dev openssl libssl-dev zlib1g-dev
>> ./configure \
  --with-http_ssl_module \
  --with-pcre
>> make -j8 && make install
  • [3] docker安装
>> docker pull nginx

2.nginx启停

  • [1] 启动nginx
>> nginx
  • [2] 查看nginx
>> ps -ef | grep nginx
  • [3] 查看端口占用
>> lsof -i:80
  • [4] 一些命令
>> nginx -s [signal]
  • signal包括:
(1) quit: 优雅停止
(2) stop: 立即停止
(3) reload: 重载配置问年间
(4) reopen: 重新打开日志文件
  • 杀掉占用端口的进程
>> sudo fuser -k 80/tcp
  • [5] 查询nginx安装信息
# 1.版本查询
>> nginx -V
# 2.软件测试
>> nginx -t

3.静态站点部署

  • [1] 查看配置文件位置
>> nginx -V # --conf-path=/etc/nginx/nginx.conf
>> nginx -t # nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
            # nginx: configuration file /etc/nginx/nginx.conf test is successful 
  • [2] 打开nginx.conf文件

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        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$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$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;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}
  • [3] 博客创建
# 1.安装hexo
>> npm install hexo-cli -g
# 2.初始化
>> hexo init blog
# 3.安装依赖
>> cd blog; npm install
# 4.生成静态站点
>> hexo g
# 5.启动本地服务器
>> hexo s
# # 4.本地运行
# >> hexo server / hexo s
  • [4] 静态站点部署
# 1.将生成public文件夹下内容复制到nginx的hyml目录下
>> sudo cp * /usr/local/nginx/html
  • [5] 浏览器进入localhost查看即可

4.配置文件

  • [1] worker_processes改为10,或设置为auto,让其自行设置:
worker_processes  10;
  • [2] 重新加载
# 1.测试配置文件是否正确
>> nginx -t
# 2.重新加载配置文件
>> nginx -s reload
  • [3] 查看nginx修改状态
>> ps -ef | grep nginx
  • [4] 文件结构:
(1) 全局块:worker进程数、指定运行服务的用户等;
(2) event块:服务器和客户端之间网络连接的一些配置,如:指定一个worker进程同时能接收多少个网络连接,网络IO模型等;
(3) http块:修改频率最频繁的块,反向代理、负载均衡等都在这个块中进行配置。http块中又可以包含多个server块(虚拟主机);

5.反向代理

  • [1] 基本概念:反向代理是相对于正向代理来说的,简单来说,正向代理就是代理客户端,反向代理就是代理服务端。
  • [2] 反向代理配置:
# 1.打开nginx.conf文件,添加如下:

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
    # 反向代理服务器:后面使用weight来调整负载均衡
    upstream backend {
      ip_hash; # 根据客户端IP地址进行hash,同一个客户端就会被分配到同一个请求上,这样就解决了一些session相关问题
      server 127.0.0.1:8000 weight=3;
      server 127.0.0.1:8001;
      server 127.0.0.1:8002;
    }

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        # 将app开头的请求都代理到配置的upstream中
        location /app {
          proxy_pass http://backend;
        }


        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        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$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$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;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
}

6.HTTPS配置

  • [1] http和https协议之间区别
(1) https协议是http协议的安全版本,它通过对传输的数据加密,来保证数据的安全性;
(2) http协议的默认端口为80,https协议的默认端口为443;
(3) https协议需要使用到SSL证书,在主流的云平台上都可以免费申请到SSL证书,证书申请完成后,会得到密钥文件和证书文件。
(4) 没有云平台时,可以使用openssl来自己生成一个自签名的证书。
  • [2] 使用openssl生成证书
# (1) 生成私钥文件(private key)
>> openssl genrsa -out private.key 2048
# (2) 根据私钥生成证书签名请求文件(certificate Signing Request, 简称CSR文件)
>> openssl req -new -key private.key -out cert.csr
# (3) 使用私钥对证书申请进行签名,从而生成证书文件(pem文件)
>> openssl x509 -req -in cert.csr -out cacert.pem -signkey private.key
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:china
String too long, must be at most 2 bytes long
Country Name (2 letter code) [AU]:中国
String too long, must be at most 2 bytes long
Country Name (2 letter code) [AU]:CN
State or Province Name (full name) [Some-State]:xiamen
Locality Name (eg, city) []:xiamen
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Geek
Organizational Unit Name (eg, section) []:Geek
Common Name (e.g. server FQDN or YOUR name) []:Mirror
Email Address []:2458006366@qq.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:cjy5201314
An optional company name []:Mirror
  • [3] 修改server配置文件

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        # 1.端口修改为tttps默认端口
        listen       443 ssl;
        server_name  localhost;
        # 2.证书名称
        ssl_certificate  /opt/mirror/etc/nginx/cacert.pem
        # 3.证书私钥文件名称
        ssl_certificate_key /opt/mirror/etc/nginx/private.key
        # 4.ssl验证配置
        ssl_session_timeout 5m;
        # 5.安全链接可选的加密协议
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TSLv1.3;
        # 6.配置加密套件/加密算法,写法遵循openssl标准
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
        # 7.使用服务器端的首选算法
        ssl_perfer_server_ciphers on;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        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$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$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;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}
  • [4] 重新启动nginx
>> nginx -s reload
  • [5] 浏览器访问:
https://localhost
  • [6] 重定向:

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    # 重定向
    server {
      listen 80;
      server_name geekhour.net www.geekhour.net;
      return 301 https://$server_name$request_uri;
    }

    server {
        # 1.端口修改为tttps默认端口
        listen       443 ssl;
        server_name  localhost;
        # 2.证书名称
        ssl_certificate  /opt/mirror/etc/nginx/cacert.pem
        # 3.证书私钥文件名称
        ssl_certificate_key /opt/mirror/etc/nginx/private.key
        # 4.ssl验证配置
        ssl_session_timeout 5m;
        # 5.安全链接可选的加密协议
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
        # 6.配置加密套件/加密算法,写法遵循openssl标准
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
        # 7.使用服务器端的首选算法
        ssl_perfer_server_ciphers on;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        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$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$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;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

7.虚拟主机

7.1 基本概念

  • 虚拟主机可以在一台服务器上部署多个站点,很多时候一个网站在起步阶段并没有非常打的访问量,将多个网站部署在一台服务器上也不会对服务器造成太大压力,而且这样可以节省服务器的资源和成本。
  • nginx的虚拟主机就是通过server块来实现的,每个server块就是一个虚拟主机,然后通过server_name来指定这个虚拟主机的域名,这样当我们访问这个域名时,就会被这个server块所匹配,然后就会执行这个server块中的配置,这样就可以在一台服务器上配置多个虚拟主机了

7.2 多个虚拟主机配置

  • [1] 在nginx路径中新建servers目录
>> sudo mkdir /usr/local/nginx/servers
  • [2] 修改nginx的conf文件,添加如下内容

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    # 重定向
    server {
      listen 80;
      server_name geekhour.net www.geekhour.net;
      return 301 https://$server_name$request_uri;
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
    # 从配置文件中载入server配置
    include servers/*;
}
  • [3] 在servers文件夹下新建一个local.conf文件,将上面的server配置剪切进去:
  server {
        # 1.端口修改为htttps默认端口
        listen       443 ssl;
        server_name  localhost;
        # 2.证书名称
        ssl_certificate  /opt/mirror/etc/nginx/cacert.pem;
        # 3.证书私钥文件名称
        ssl_certificate_key /opt/mirror/etc/nginx/private.key;
        # 4.ssl验证配置
        ssl_session_timeout 5m;
        # 5.安全链接可选的加密协议
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
        # 6.配置加密套件/加密算法,写法遵循openssl标准
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
        # 7.使用服务器端的首选算法
        ssl_perfer_server_ciphers on;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        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$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$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;
        #}
    }
  • [4] 重载配置文件:
>> nginx -s reload
  • [5] 多个虚拟主机,就是在servers文件夹下再新建几个配置文件,并进行配置。

8.错误处理

  • [1] nginx: [emerg] bind() to 0.0.0.0:80 failed (13: Permission denied)
# 1.进入可执行文件路径
>> cd /usr/local/nginx/sbin/ 
# 2.change owner:设置文件所有者为root
>> sudo chown root nginx
# 3.让用户和拥有者具有同样权限
>> sudo chmod u+s nginx

参考资料


评论