Apache/Nginx基本使用

nginx

nginx启动,停止,重启

nginx  -t             #测试nginx的配置文件(nginx.conf)
nginx -s stop         #停止
nginx -s reload       #重启
kill -9 nginx         #强制停止  

nginx.conf说明

  • 反向代理
location / {    # / 表示需要代理的路径,可以修改
   proxy_pass  '需代理服务器地址';
}
  • 证书配置
listen 443 ssl [http2];
server_name chenggang.win www.chenggang.win;

# 证书私钥
ssl_certificate_key /etc/nginx/ssl-root/live/chenggang.win/privkey.pem;
# 证书名称
ssl_certificate /etc/nginx/ssl-root/live/chenggang.win/fullchain.pem;
  • http跳转https
server {
   listen 80;
   server_name chenggang.win;
   return 301 https://$server_name$request_uri;
}
  • https证书域名验证
location ^~ /.well-known/acme-challenge/ {
    default_type text/plain; # 设置响应类型
    root  /etc/nginx/ssl-root;
}

location = /.well-known/acme-challenge/ {
    return 404;
}
  • 开启gzip
# gzip
gzip            on;
gzip_vary       on;
gzip_proxied    any;
gzip_comp_level 6; # 压缩级别
gzip_types      text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml;
  • 静态资源处理
# favicon.ico
location = /favicon.ico {
  log_not_found off;
  access_log    off;
}

# robots.txt
location = /robots.txt {
  log_not_found off;
  access_log    off;
}

# assets, media
location ~* \.(?:css(\.map)?|js(\.map)?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
  expires    7d;
  access_log off;
}

# svg, fonts
location ~* \.(?:svgz?|ttf|ttc|otf|eot|woff2?)$ {
  add_header Access-Control-Allow-Origin "*";
  expires    7d;
  access_log off;
}

# never cache .html
# https://stackoverflow.com/questions/49547/how-do-we-control-web-page-caching-across-all-browsers/2068407#2068407
location / {
  if ($request_filename ~* .*\.(?:htm|html)$) {
    add_header Cache-Control "private, no-store, no-cache, must-revalidate, proxy-revalidate";
  }
  
  root /web;
}
  • root目录和alias(虚拟)目录说明

root与alias主要区别在于nginx如何解析location后面的uri,root则是最上层目录的定义,而alias是一个目录别名的定义。

解析方式:
root: root路径+location路径
alias: 使用alias路径替换location路径

建议使用场景:
在location /中配置root目录
在location /path中配置alias虚拟目录

example:

#root
server {
  listen 80;
  server_name a.com;
  
  # 访问 http://a.com/static/image/b.jpg,
  # nginx会去 /static/static/image/b.jpg路径查找资源,即root路径+location路径
  
  # root指定的目录是location匹配访问的path目录的上一级目录,
  # 这个path目录一定要是真实存在root指定的目录下
  
  location /static {
    # 若查找路径为/static/image/b.jpg,则需改为 / 即可
    root /static;
  }
}

#alias
server {
  listen 80;
  server_name a.com;

  # 访问 http://a.com/static/image/b.jpg,
  # nginx会去 /static/image/b.jpg路径查找资源,即直接替换location路径
  # alias指定的目录后面必须要加上 / 符号
  location /static/ {
    alias /static/;
  }
}
  • SPA配置
location / {
  root  /web/dist;
  index  index.html;
  try_files $uri $uri/ /index.html;
}
  • 负载均衡
http {
  upstream myapp1 {
    server srv1.example.com weight=3; # weight可以设置权重
    server srv2.example.com;
    server srv3.example.com;
  }

  server {
    listen 80;

    location / {
      proxy_pass http://myapp1;
    }
  }
}

禁止IP访问,只能域名访问

server {
  listen 80 default;
  server_name _;
  return 403;
}

server {
  listen 80;
  server_name a.com;
  root /html;
  index a.html;
}

apache

安装(window)

  • apache 官网已经不提供window版的二进制安装包,但提供推荐的其他网站的二进制安装包
  • 修改配置文件httpd.conf中的apache的安装目录
  • 运行httpd -k install安装成系统服务
  • 运行httpd -k start启动服务器

开启vhost

1 启用vhost配置 Include conf/extra/httpd-vhosts.conf
2 打开端口

Listen 80
Listen 81
# ...

3 修改默认配置 (httpd.conf和httpd-vhost.conf共用相同的端口后者会覆盖前者)

设置代理(两种情况)

1 若配置文件为httpd.conf

  • 开启代理模块mod_proxy.so,mod_proxy_http.so,mod_proxy_balancer
  • http.conf的最后添加如下两行或者vhost.conf也是类似配置
ProxyPass /api http://some.example.com  #根据自己的需求修改
ProxyPassReverse /api http://some.example.com

2 若配置文件为apache2.conf

  • 开启代理模块(有三种方式)
    • 直接在apache2.conf中添加模块
    • 建立软连接
    ln -s /etc/apache2/mods-available/proxy.load /etc/apache2/mods-enabled/proxy.load
    ln -s /etc/apache2/mods-available/proxy_http.load /etc/apache2/mods-enabled/proxy_http.load
    ln -s /etc/apache2/mods-available/proxy_balancer.load /etc/apache2/mods-enabled/proxy_banancer.load
    
    • 使用命令开启
      • a2enmod proxy proxy_balancer proxy_http
      • 在 /etc/apache2/sites-enabled/000-default.conf中添加
#off表示开启反向代理,on表示开启正向代理
ProxyRequests Off
#反代理要解析的ip 支持添加端口 
ProxyPass / http://172.16.168.35:7001/        
ProxyPassReverse / http://172.16.168.35:7001/

定义/使用变量

Define Root "/usr/local/apache2/htdocs" 
# ...

# 配置文件中路径需要加引号
<Directory "${Root}/slop">
# ...
</Directory>

加载php模块

LoadModule php7_module "*****/php7apache2_4.dll" (模块位置在php的安装路径)

启动、停止和重启

  • 基本的操作方法:

    • 启动:/usr/local/apache2/bin/apachectl start
    • 停止:/usr/local/apache2/bin/apachectl stop
    • apache重新启动命令:/usr/local/apache2/bin/apachectl restart
    • 要在重启 Apache 服务器时不中断当前的连接,则应运行:/usr/local/sbin/apachectl graceful
  • 如果apache安装成为linux的服务的话,可以用以下命令操作:
    service httpd start 启动
    service httpd restart 重新启动
    service httpd stop 停止服务

  • Linux系统为Ubuntu

  • 启动: /etc/init.d/apache2 start
  • 重启: /etc/init.d/apache2 restart
  • 停止:/etc/init.d/apache2 stop

SPA配置

开启rewrite模块 mod_rewrite.so

  • 方式1: vhost中配置
<Directory "path/to/dir">
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</Directory>
  • 方式2:.htaccess配置
  1. 在配置文件中开启权限
<Directory "/usr/local/apache2/htdocs/web">
  AllowOverride All
  Require all granted
</Directory>
  1. 在应用根目录创建.htaccess文件并写入以下内容
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

开启同一端口多站点

主要是配置不同的 ServerName

<VirtualHost *:80>
  DocumentRoot "path/to/dir1"
  ServerName aaa.com
  ServerAlias www.aaa.com
  ErrorLog "logs/aaa.com-error_log"
  CustomLog "logs/aaa.com-access_log" common
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot "path/to/dir2"
  ServerName bbb.com
  ServerAlias www.bbb.com
  ErrorLog "logs/bbb.com-error_log"
  CustomLog "logs/bbb.com-access_log" common
</VirtualHost>

禁止IP访问,只能域名访问

注意:主配置文件的默认站点也要更改权限,禁止访问,否则会访问到默认站点

原理:新增虚拟主机的serverName为localhost或者127.0.0.1,限制其访问权限

<VirtualHost *:80>
  ServerName localhost
  <Directory />
    AllowOverride none
    Require all denied
  </Directory>
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot "path/to/dir"
  ServerName aaa.com
  ServerAlias www.aaa.com
  ErrorLog "logs/aaa.com-error_log"
  CustomLog "logs/aaa.com-access_log" common
</VirtualHost>

目录结构(Linux)

/etc/apache2/
|-- apache2.conf 主配置文件,用来组合各个配置文件
|-- ports.conf 端口设置
|-- mods-enabled
|       |-- *.load
|       |-- *.conf
|-- conf-enabled
|       |- *.conf
|-- sites-enabled
|       |-- *.conf

     
 说明: *-available 表示可以配置,*-enabled 表示已启用的配置,实际是
 *-available的软链接,a2enmod, a2dismod, a2ensite, a2dissite, and a2enconf, a2disconf 用这些命令可以**管理配置**

常用的配置模板

# 定义变量
Define WORKDIR "{指定目录}"

<VirtualHost *:8099>
   ServerAdmin iron
   DocumentRoot "${WORKDIR}"
   ServerName localhost
   ServerAlias localhost
   ErrorLog ${APACHE_LOG_DIR}/error.log
   CustomLog ${APACHE_LOG_DIR}/access.log common

   # set access right
   <Directory "${WORKDIR}">
        AllowOverride All      # 允许.htaccess 重写
        Require all granted
   </Directory>
   
   ProxyPass /api http://****
   ProxyPassReverse /api http://****
   
   # never cache index.html file
   <FilesMatch "index\.(html|htm)$">
     <IfModule mod_headers.c>
       Header set Cache-Control "no-cache, no-store, must-revalidate"
       Header set Pragma "no-cache"
       Header set Expires 0
     </IfModule>
   </FilesMatch>
</VirtualHost>

生成自签名证书

  1. 生成2048位的加密私钥(server.key)
    openssl genrsa -out server.key 2048
  2. 生成证书签名请求(server.csr)
    openssl req -new -key server.key -out server.csr -config openssl.cnf
  3. 生成类型为X509的自签名证书。有效期设置3650天,即有效期为10年
    openssl x509 -req -days 3650 -in server.csr -signkey server.key -out server.crt

HTTPS免费证书

  1. 免费证书letsencrypt,推荐生成证书客户端zerosslacme-nginx
  2. 利用docker生成
  • 编写docker-compose.yml
version: '3.8'

services:
  ssl:
    image: certbot/certbot
    volumes:
      - ./content:/etc/letsencrypt
      - ./lib:/var/lib/letsencrypt
    # preferred-challenges=dns 优先使用dns验证
    command: certonly --manual --preferred-challenges=dns
  • run docker-compose run ssl

中文域名转换

服务器在配置中文域名时需要进行Punycode转码才能正常使用,转码地址punycoder

参考