配置apache, nginx 支持 angular2+ 等单网页项目路由刷新 作者:七棵菜 日期:2022-11-30 栏目:计算机分类:90 人气:625 `angular2+`的项目打包部署到服务器上之后需要重写服务器路由规则,否则在刷新页面的时候会出现`404`错误。 #### nginx的配置方法 ``` location / { try_files $uri $uri/ /index.html; } # 子目录 location /xuncha-test/ { alias /usr/share/nginx/html/xuncha-test/; try_files $uri $uri/ /xuncha-test/index.html; index index.html index.htm; } ``` 完整配置如下: ``` server { listen 80; server_name admin.xindejob.localhost; root /data/www/xindejob/frontend/admin; index index.html index.htm; #charset koi8-r; #access_log /var/log/nginx/access.log main; access_log off; location / { try_files $uri $uri/ /index.html; } location ~* \.(?:js|css|png|jpg|jpeg|gif|ico)$ { expires max; add_header Pragma public; add_header Cache-Control "public, must-revalidate, proxy-revalidate"; log_not_found off; tcp_nodelay off; break; } location ~ .*\.(eot|ttf|ttc|otf|eot|woff|woff2|svg)(.*){ add_header Access-Control-Allow-Origin http://game-admin.shaimobao.com; } location /api { rewrite ^/api/(.*)$ /$1 break; proxy_pass http://access.cultural-treasure.localhost/; } } ``` #### apache的配置方法 可以在项目根目录中增加`.htaccess`文件,但是需要更改代码,有耦合,不推荐。 推荐的方法是在服务器中增加重写规则,有以下两点需要注意 > `Options`: 禁用*Indexes*和*ExecCGI*;不能禁用*FollowSymLinks*,否则会报*403*错误 `mod_rewrite`模块必须开启 重写规则有以下两种方法: ``` RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] ``` ``` RewriteEngine On # 如果请求的是现有资源,则按原样执行 RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d RewriteRule ^ - [L] # 如果请求的资源不存在,则使用index.html RewriteRule ^ /index.html ``` 完整配置如下: ``` <VirtualHost _default_:80> DocumentRoot "D:\workspace\demo\angular\base-admin\dist\full" ServerName full.ngx-admin.localhost <Directory "D:\workspace\demo\angular\base-admin\dist\full"> Options -Indexes -ExecCGI AllowOverride All Order allow,deny Allow from all Require all granted <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </IfModule> </Directory> ProxyPass /api http://seven-food.localhost/access </VirtualHost> ``` 标签: apache nginx SPA 上一篇:如何使用mvn命令导入依赖 下一篇:git fatal: Could not read from remote repository. 随便看看 2022-11-30 配置apache, nginx 支持 angular2+ 等单网页项目路由刷新 2023-08-16 nginx配置angular项目部署在项目子目录 2022-11-30 设置 .gitignore 不忽略文件夹的规则 2022-11-30 git查看某文件最近的修改内容 2022-11-30 实现 git 切换分支后代码互不影响 留言