Linux使用nginx快速搭建前端页面

linux使用nginx快速搭建前端页面

最新版本查看 nginx官网

准备工作

  • 服务器常运行
  • ssh连接上

1. 查看是否安装过nginx

//安过会显示nginx目录
whereis nginx

//卸载旧的
yum remove nginx

2. 安装rpm包

//添加源
sudo rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm

//安装nginx
sudo yum install -y nginx

//是否安装成功, 查看版本
nginx -v

3. 查看和修改配置

//检测nginx配置是否成功
nginx -t

//会输出如下表明配置文件ok
> nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
> nginx: configuration file /etc/nginx/nginx.conf test is successful
  • 修改配置文件1 /etc/nginx/nginx/conf 如下:
#用户默认是 nginx 改为 root
user  root; 
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/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  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

	#默认配置
    include /etc/nginx/conf.d/*.conf;
}

  • 修改配置文件2 /etc/nginx/conf.d/default.conf
server {
	#默认80,可以自定义
    listen       80; 
    server_name  localhost 127.0.0.1;

	#跨域访问, 实测没有任何效果
	add_header Access-Control-Allow-Origin '*' always; 

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

	#配置根路径 root指向你的前端文件夹路径, 默认打开index文件
    location / {
				add_header 'Access-Control-Allow-Origin' '*' always;
        root   /root/web/html;
        index  index.html index.htm;
    }
	
	#如果像我一样, 前端和后台都在同一台服务器, 代理直接写后台接口IP:端口
	#访问路径中含/api/XXX方法的(假如api下的都是后台接口),会默认代理到上面定义的80端口,避免前端页面请求跨域问题
    location /api/ {
			add_header 'Access-Control-Allow-Origin' '*' always;
			proxy_pass http://localhost:8081;
    }


    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    
    #nginx错误页面, 一般不改
    location = /50x.html {
        root   /usr/share/nginx/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

//启动nginx ,默认80端口, 直接输入nginx回车
nginx

//访问ip,默认页面路径(可在配置文件中替换)
/usr/share/nginx/html

5. 关闭防火墙

//关闭防火墙适用于tomcat,nginx等
vim /etc/sysconfig/iptables

#增加80端口(上面自定义的端口)
-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT

//重启防火墙
service iptables restart 

//查看状态
service iptables status

6. 常见问题

//查看错误日志,定位问题
cd /var/log/nginx
cat error.log
  • 报错403 forbidden (13: Permission denied)
//由于启动用户和nginx工作用户不一致所致,查看nginx的启动用户
ps aux | grep "nginx: worker process" | awk  '{print $1}'
nginx
root

//发现是nginx,而不是用root启动的, 将 nginx.conf 的 user 改为和启动用户一致
将/etc/nginx/nginx.conf文件中第一行的 user 对应的 nginx 改为 root ,改完后重启
nginx -s reload
  • 端口占用
//nginx启动后可查看端口占用情况, 如果冲突自行kill
netstat -ntlp
  • 内存占满
//删除linux内存缓存
echo 3 > /proc/sys/vm/drop_caches
  • 关于前端跨域访问接口问题

首先在用工具get/post请求等确定可以正常返回的情况下, 解决浏览器跨域请求的两种办法

  1. 前端页面使用axios请求代替ajax;
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/axios/0.19.0/axios.min.js"></script>
<script type="text/javascript">
    function test() {
        axios.post('/api/test', {param:'test'})
            .then(function (response) {
                console.log(response);
                //$('#json').html(JSON.stringify(response))
            })
            .catch(function (error) {
                console.log(error);
            });
    };
		
  // function test() {
  //     $.ajax({
  //       url: '/api/test',
  //       type: "GET",
  //       contentType: 'application/json;charset=utf-8',
  //       data: {param:'test'},
  //       success: function (r) {
  //         console.log(response);
  //         //$('#json').html(JSON.stringify(response))
  //       }
  //   });
  // }

</script>
  1. 后台增加允许跨域访问;
//在Application中实现WebMvcConfigurer接口, 重写addCorsMappings方法
@Override
public void addCorsMappings(CorsRegistry registry) {
  //增加允许访问
  registry.addMapping("/**")
    .allowCredentials(true)
    .allowedHeaders("*")
    .allowedOrigins("*")
    .allowedMethods("*");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值