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、打开浏览器访问域名
打开浏览器访问对应的域名,出现对应的页面即可