在您的 Node.js Beanstalk 应用程序中,您的实例的 /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf 设置如下:
server {
listen 8080;
location / {
proxy_pass http://nodejs;
proxy_set_header Connection "";
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
gzip on;
}
你想要的是这样设置:
server {
listen 8080;
location / {
proxy_pass http://nodejs;
proxy_set_header Connection "";
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
gzip on;
}
在 /etc/nginx/.htpasswd 有一个单独的密码文件,其中包含您的登录凭据。
第 1 步:
进入你本地的linux环境,进入
sudo htpasswd -c .htpasswd someusernameofyourchoice
导航到该 .htpasswd 文件并提取您生成的用户名和密码行。它看起来像这样:
someusernameofyourchoice:$apr1$.1EAU7DD$rt9jdihy1U.cFuBzJTMed.
第 2 步:
现在在您的节点应用程序的根目录(您的 .git/ 目录所在的位置)创建一个名为 .ebextensions/ 的隐藏目录
导航到 .ebextensions/ 目录,因为您需要创建 2 个文件。
第 3 步:
第一个文件将是配置文件,它将在您的 beanstalk 应用程序上生成您的 .htpasswd 文件。将您之前生成的用户名和密码哈希放入此文件中,并将其命名如下:
00_nginx_htpasswd.config
files:
"/etc/nginx/.htpasswd" :
mode: "000755"
owner: root
group: root
content: |
someusernameofyourchoice:$apr1$.1EAU7DD$rt9jdihy1U.cFuBzJTMed.
第 4 步:
您将在 .ebextensions/ 目录中创建的第二个文件将更新弹性 beanstalk 环境中的 00_elastic_beanstalk_proxy.conf 文件。名称如下:
01_nginx_auth.config
files:
/tmp/deployment/nginx_auth.sh:
mode: "000755"
content: |
sed -i 's/$proxy_add_x_forwarded_for;/$proxy_add_x_forwarded_for;\n auth_basic "Restricted";\n auth_basic_user_file \/etc\/nginx\/.htpasswd;\n/' /tmp/deployment/config/#etc#nginx#conf.d#00_elastic_beanstalk_proxy.conf
container_commands:
nginx_auth:
command: "/tmp/deployment/nginx_auth.sh"
注意:如果您只希望密码保护在特定环境(例如您的开发环境)上。您可以将环境变量传递到您的环境中(在 beanstalk 仪表板上的配置 > 软件配置面板中),然后您可以向该文件的命令添加一个条件,在该环境变量运行之前检查该环境变量。通过这种方式,您可以使用密码保护您的开发环境,同时让您的生产环境免费供公众访问。当您将所有内容放入 git 以将其推送到您的 beanstalk 环境时,这非常方便。以下是修改后的文件,添加了这些内容:
01_nginx_auth.config
files:
/tmp/deployment/nginx_auth.sh:
mode: "000755"
content: |
if [ "$NODE_ENV" == "development" ]; then
sed -i 's/$proxy_add_x_forwarded_for;/$proxy_add_x_forwarded_for;\n auth_basic "Restricted";\n auth_basic_user_file \/etc\/nginx\/.htpasswd;\n/' /tmp/deployment/config/#etc#nginx#conf.d#00_elastic_beanstalk_proxy.conf
fi
container_commands:
nginx_auth:
command: "/tmp/deployment/nginx_auth.sh"
第 5 步:
在 .ebextensions/ 目录中创建这两个文件后,提交它们并将它们推送到弹性 beanstalk。现在应该会提示您输入在第 1 步中生成的用户名和密码组合。