我使用 Angular-CLI 创建一个测试应用程序并使用 Nginx 为其提供服务。得到 404 或 403。我猜这是我的 Nginx 配置的问题,但为了额外确定,我已经提供了达到这一点所执行的所有步骤。
这些是我遵循的步骤:
安装的角度-cli:npm install -g @angular/cli
开始了一个新项目:ng new test-angular
检查使用ng-serve
它有效。
构建要使用 nginx 提供服务的项目:ng build
。创建一个dist
项目目录中的文件夹。
-
更改了我的 nginx 配置:
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
server {
listen 80 default_server;
root /home/mellkor/test-angular/dist;
index index.html index.htm;
server_name localhost;
location / {
try_files $uri $uri/ =404;
}
}
}
nginx -s reload
成功的。击中时localhost
,我收到 404 Not Found。
根据一些建议,更改为try_files $uri /index.html
给我一个 403 Forbidden。
另一个问题:自从ng init
似乎不再工作了,如何初始化现有的 Angular2 应用程序并使用 Angular-CLI 将其构建到生产环境?
是的,我确实提到了this https://github.com/angular/angular-cli/issues/4269已关闭主题,但到目前为止还没有解决方案。
附加信息:
@angular/cli: 1.0.0-rc.0
node: 7.5.0
os: linux x64
@angular/common: 2.4.8
@angular/compiler: 2.4.8
@angular/core: 2.4.8
@angular/forms: 2.4.8
@angular/http: 2.4.8
@angular/platform-browser: 2.4.8
@angular/platform-browser-dynamic: 2.4.8
@angular/router: 3.4.8
@angular/cli: 1.0.0-rc.0
@angular/compiler-cli: 2.4.8
可能有一种可能性,这就是您收到错误 404/403 的原因:
- index.html head 标签中的基本 href 错误
- ng build 命令时错误的 --base-href 值
- 错误的 nginx 配置(即服务器根目录或服务器位置/)
- Nginx 必须提供的文件(即 /dist 文件夹)的权限错误
这是解决方案:
假设您想在 HOST 部署 Angular 应用程序:http://example.com
和端口:8080
注意 - HOST 和 PORT 在您的情况下可能不同。
确保你有<base href="/">
在你的index.html head标签中。
另外,请检查您是否对 Nginx 必须提供服务的 /dist 文件拥有正确的权限。这里是help https://stackoverflow.com/questions/6795350/nginx-403-forbidden-for-all-files.
首先,转到您计算机上的 Angular 存储库(即 /home/user/helloWorld)路径。
-
然后使用以下命令为您的生产服务器构建 /dist:
ng build --prod --base-hrefhttp://example.com:8080 http://example.com:8080
现在将 /dist (即 /home/user/helloWorld/dist)文件夹从计算机的 Angular 存储库复制到要托管生产服务器的远程计算机。
-
现在登录到您的远程服务器并添加以下 nginx 服务器配置。
server {
listen 8080;
server_name http://example.com;
root /path/to/your/dist/location;
# eg. root /home/admin/helloWorld/dist
index index.html index.htm;
location / {
try_files $uri $uri/ /index.html;
# This will allow you to refresh page in your angular app. Which will not give error 404.
}
}
现在重新启动 nginx。
就是这样 !!现在您可以访问您的角度应用程序http://example.com:8080 http://example.com:8080
希望它会有所帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)