Mac

安装

brew install nginx

路径

安装路径:/usr/local/Cellar/nginx/1.17.6image.png

服务器默认路径:/usr/local/var/www
image.png

配置文件路径:/usr/local/etc/nginx
image.png

启动

/usr/local/Cellar/nginx/1.17.6/bin/nginx -c /usr/local/etc/nginx/nginx.conf
image.png

查看网页http://localhost:8080/看是否启动成功
image.png

或者查看进程 ps -ef|grep nginx 如果master进程启动则是成功的
image.png

配置文件

默认配置文件
nginx.conf

  1. worker_processes 1;
  2. #pid logs/nginx.pid;
  3. events {
  4. worker_connections 1024;
  5. }
  6. http {
  7. include mime.types;
  8. default_type application/octet-stream;
  9. #access_log logs/access.log main;
  10. sendfile on;
  11. keepalive_timeout 65;
  12. server {
  13. listen 8080;
  14. server_name localhost;
  15. location / {
  16. root html;
  17. index index.html index.htm;
  18. }
  19. error_page 500 502 503 504 /50x.html;
  20. location = /50x.html {
  21. root html;
  22. }
  23. }
  24. include servers/*;
  25. }

注意http块里有一句 include servers/*; 所以我们自己的应用的配置文件可以放在servers文件夹下。
image.png

CentOS7

安装

sudo yum install -y nginx

启动

sudo systemctl start nginx 启动
sudo systemctl status nginx 状态
sudo systemctl stop nginx 停止
sudo systemctl enable nginx 开机启动

路径

安装路径:/usr/sbin/nginx
image.png
配置文件:/etc/nginx
image.png

服务器默认路径:/usr/share/nginx/html
image.png

日志文件:/var/log/nginx (需root权限才能访问)
image.png

配置文件

  1. http {
  2. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  3. '$status $body_bytes_sent "$http_referer" '
  4. '"$http_user_agent" "$http_x_forwarded_for"';
  5. access_log /var/log/nginx/access.log main;
  6. sendfile on;
  7. tcp_nopush on;
  8. tcp_nodelay on;
  9. keepalive_timeout 65;
  10. types_hash_max_size 2048;
  11. include /etc/nginx/mime.types;
  12. default_type application/octet-stream;
  13. include /etc/nginx/conf.d/*.conf;
  14. server {
  15. listen 80 default_server;
  16. listen [::]:80 default_server;
  17. server_name _;
  18. root /usr/share/nginx/html;
  19. # Load configuration files for the default server block.
  20. include /etc/nginx/default.d/*.conf;
  21. location / {
  22. }
  23. error_page 404 /404.html;
  24. location = /40x.html {
  25. }
  26. error_page 500 502 503 504 /50x.html;
  27. location = /50x.html {
  28. }
  29. }
  30. }

注意:用户自己的配置文件请放在/etc/nginx/conf.d/目录下。

常见问题

  1. 403 forbidden

解决:打开nginx.conf文件,将 user nginx 改成 nginx root , 并且保证root用户对你的应用具有访问权限


源码编译安装

为什么要通过编译源码的方式安装 nginx 呢?因为我想要安装第三方模块 http_sub_module

在默认的发行版中,是没有 http_sub_module 模块的,所以只能学习怎么通过编译源码的方式安装了。

源码地址

源码地址入口:https://nginx.org/en/download.html

安装 - 图12

访问代码仓库:http://hg.nginx.org/nginx,找到一个想要的版本单击,然后点击旁边的zip包或者gz包

安装 - 图13

安装 - 图14

源码编译

  1. 解压tar -zxvf nginx-7d46c9f56c9a.tar.gz,目录如下图所示
    安装 - 图15
  2. 执行命令./auto/configure --with-http_sub_module ,其中--with-http_sub_module用于安装第三方模块(官网地址参照https://nginx.org/en/docs/configure.html
    执行完上述命令后,会生成一个Makefile,如下图所示
    安装 - 图16
  3. 使用make命令
  4. 然后再sudo make install,查看/usr/local即可看到nginx已安装完成。
  5. sudo ./sbin/nginx 启动