Nginx配置虚拟主机(配置域名)

Nginx配置虚拟主机(配置域名)

1、打开Nginx的配置文件,配置文件在Nginx的安装目录下的conf文件

在Http端内添加一下配置,包含conf.d下后缀名为conf的文件(注意位置不要写错了),和http端内,和server平级

http{
     server{
     }
     # 包含conf.d目录下以conf结尾的文件
    include conf.d/*.conf;
}
2、在nginx的conf目录下,添加目录conf.d目录
mkdir conf.d
3、跳转conf.d目录下,新建一个以conf结尾的文件

这里以www.mylaravel.com为例子

# 创建虚拟主机文件
touch www.mylaravel.com.conf

# 编辑虚拟主机配置文件
vim www.mylaravel.com.conf

# 在文件中添加server
server {
    # 监听的端口号
    listen 80;
    # 服务的名称  域名
    server_name www.mylaravel.com;
    # 访问日志
    access_log /data/wwwlogs/www.mylaravel.com_access_nginx.log combined;
    # 错误日志
    error_log /data/wwwlogs/www.mylaravel.com_error_nginx.log;
    # 打开目录访问
    autoindex on;
    autoindex_localtime on;
    # 根目录 要访问的文件放的地方
    root /data/wwwroot/default/mylaravel;
    # 默认访问的页面 优先访问index.html 不存在访问index.htm 不存在访问index.php
    index index.html index.htm index.php;
    # 设置404错误页面
    error_page 404 /404.html;
    # 设置502页面
    error_page 502 /502.html;
	# 配置nginx重写
	location / {
 	    try_files $uri $uri/ /index.php?$query_string;
    }
    # Nginx错误状态 不记录日志
    location /nginx_status {
      access_log off;
      allow 127.0.0.1;
      deny all;
    }
    # 设置php的请求交给 php-fpm 转交9000端口
    location ~ \.php$ {
      fastcgi_pass 127.0.0.1:9000;
      #fastcgi_pass unix:/dev/shm/php-cgi.sock;
      fastcgi_index index.php;
      include fastcgi.conf;
    } 
    # 设置静态文件 缓存30天
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ {
      # 验证来源  【防盗链】
      valid_referers www.mylaravel.com mylaravel.com;
      set $error 0;
      # 验证涞源是不是规定的域名,不是设置错误为2
      if ($invalid_referer) {
             set $error 2;
      }
      # 验证是否是防盗链的图,是的话设置错误为1 不走重写
      if ($request_uri ~* no.png) {
         set $error  1;
      }
      # 错误为2 说明是其他域名过来的请求
      if ($error = 2) {
             # 重写到no.png 
             rewrite ^/ http://www.mylaravel.com/no.png;
             # 返回404错误,重写和404返回一个即可
             #return 404;
      }
      # gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico 文件不记录访问日志
      access_log off;
    }
    # js css缓存9天 并且不记录访问日志
    location ~ .*\.(js|css)?$ {
      expires 7d;
      access_log off;
    }
    # 所有以 .ht开始文件不允许访问
    location ~ /\.ht {
      deny all;
    }
  }
4、重启Nginx
/usr/local/nginx/sbin/nginx -s reload
5、本地配置Host访问该域名
windows

本地如果是windows系统,打开host域名执行文件,一般情况下目录在C:\WINDOWS\system32\etc\hosts
添加域名执行格式是:

#ip 域名
10.0.0.1 www.mylaravel.com
Linux或者是Mac

打开Hosts文件

vim /etc/hosts
#ip 域名
10.0.0.1 www.mylaravel.com
6、打开浏览器访问域名

打开浏览器访问对应的域名,出现对应的页面即可

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奇葩也是花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值