发布Asp.net core到nginx 使用nginx代理
In this guide, we will cover setting up a production-ready ASP.NET environment on an Ubuntu 16.04 Server.+
Note
For Ubuntu 14.04 supervisord is recommended as a solution for monitoring the Kestrel process. systemd is not available on Ubuntu 14.04. See previous version of this document
We will take an existing ASP.NET Core application and place it behind a reverse-proxy server. We will then setup the reverse-proxy server to forward requests to our Kestrel web server.
Additionally we will ensure our web application runs on startup as a daemon and configure a process management tool to help restart our web application in the event of a crash to guarantee high availability.
Prerequisites
Access to an Ubuntu 16.04 Server with a standard user account with sudo privilege.
An existing ASP.NET Core application.
Copy over your app
Run dotnet publish from your dev environment to package your application into a self-contained directory that can run on your server.2
Before we proceed, copy your ASP.NET Core application to your server using whatever tool (SCP, FTP, etc) integrates into your workflow. Try and run the app and navigate to http://<serveraddress>:<port> in your browser to see if the application runs fine on Linux. I recommend you have a working app before proceeding.
Note
You can use Yeoman to create a new ASP.NET Core application for a new project.
Configure a reverse proxy server
A reverse proxy is a common setup for serving dynamic web applications. The reverse proxy terminates the HTTP request and forwards it to the ASP.NET application.
Why use a reverse-proxy server?
Kestrel is great for serving dynamic content from ASP.NET, however the web serving parts aren’t as feature rich as full-featured servers like IIS, Apache or Nginx. A reverse proxy-server can allow you to offload work like serving static content, caching requests, compressing requests, and SSL termination from the HTTP server. The reverse proxy server may reside on a dedicated machine or may be deployed alongside an HTTP server.
For the purposes of this guide, we are going to use a single instance of Nginx that runs on the same server alongside your HTTP server. However, based on your requirements you may choose a different setup.
When setting up a reverse-proxy server other than IIS, you must call app.UseIdentity (in Configure) before any other external providers.
Because requests are forwarded by reverse-proxy, use ForwardedHeaders middleware (from Microsoft.AspNetCore.HttpOverrides package) in order to set the redirect URI with the X-Forwarded-For and X-Forwarded-Proto headers instead of Request.Scheme and Request.Host."
Add UseForwardedHeaders to Configure before calling app.UseFacebookAuthentication or similar:
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
Install Nginx
sudo apt-get install nginx
Note
If you plan to install optional Nginx modules you may be required to build Nginx from source.
We are going to apt-get to install Nginx. The installer also creates a System V init script that runs Nginx as daemon on system startup. Since we just installed Nginx for the first time, we can explicitly start it by running
sudo service nginx start
At this point you should be able to navigate to your browser and see the default landing page for Nginx.
Configure Nginx
We will now configure Nginx as a reverse proxy to forward requests to our ASP.NET application
We will be modifying the /etc/nginx/sites-available/default, so open it up in your favorite text editor and replace the contents with the following.
server {
listen 80;
location / {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
This is one of the simplest configuration files for Nginx that forwards incoming public traffic on your port 80 to a port 5000 that your web application will listen on.
Once you have completed making changes to your nginx configuration you can run sudo nginx -t to verify the syntax of your configuration files. If the configuration file test is successful you can ask nginx to pick up the changes by running sudo nginx -s reload.
Monitoring our application
Nginx is now setup to forward requests made to http://localhost:80 on to the ASP.NET Core application running on Kestrel at http://127.0.0.1:5000. However, Nginx is not set up to manage the Kestrel process. We will use systemd and create a service file to start and monitor the underlying web app. systemd is an init system that provides many powerful features for starting, stopping and managing processes.
Create the service file
Create the service definition file
sudo nano /etc/systemd/system/kestrel-hellomvc.service
An example service file for our application.
[Unit]
Description=Example .NET Web API Application running on Ubuntu
[Service]
WorkingDirectory=/var/aspnetcore/hellomvc
ExecStart=/usr/bin/dotnet /var/aspnetcore/hellomvc/hellomvc.dll
Restart=always
RestartSec=10 # Restart service after 10 seconds if dotnet service crashes
SyslogIdentifier=dotnet-example
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
[Install]
WantedBy=multi-user.target
Note
User -- If the user www-data is not used by your configuration, the user defined here must be created first and given proper ownership for files
Save the file and enable the service.1
systemctl enable kestrel-hellomvc.service
Start the service and verify that it is running.
systemctl start kestrel-hellomvc.service
systemctl status kestrel-hellomvc.service
● kestrel-hellomvc.service - Example .NET Web API Application running on Ubuntu
Loaded: loaded (/etc/systemd/system/kestrel-hellomvc.service; enabled)
Active: active (running) since Thu 2016-10-18 04:09:35 NZDT; 35s ago
Main PID: 9021 (dotnet)
CGroup: /system.slice/kestrel-hellomvc.service
└─9021 /usr/local/bin/dotnet /var/aspnetcore/hellomvc/hellomvc.dll
With the reverse proxy configured and Kestrel managed through systemd, the web application is fully configured and can be accessed from a browser on the local machine at http://localhost. Inspecting the response headers, the Server still shows the ASP.NET Core application being served by Kestrel.
HTTP/1.1 200 OK
Date: Tue, 11 Oct 2016 16:22:23 GMT
Server: Kestrel
Keep-Alive: timeout=5, max=98
Connection: Keep-Alive
Transfer-Encoding: chunked
Viewing logs
Since the web application using Kestrel is managed using systemd, all events and processes are logged to a centralized journal. However, this journal includes all entries for all services and processes managed by systemd. To view the kestrel-hellomvc.service specific items, use the following command.
sudo journalctl -fu kestrel-hellomvc.service
For further filtering, time options such as --since today, --until 1 hour ago or a combination of these can reduce the amount of entries returned.
sudo journalctl -fu kestrel-hellomvc.service --since "2016-10-18" --until "2016-10-18 04:00"
Securing our application
Enable AppArmor
Linux Security Modules (LSM) is a framework that is part of the Linux kernel since Linux 2.6 that supports different implementations of security modules. AppArmor is a LSM that implements a Mandatory Access Control system which allows you to confine the program to a limited set of resources. Ensure AppArmor is enabled and properly configured.
Configuring our firewall
Close off all external ports that are not in use. Uncomplicated firewall (ufw) provides a frontend for iptables by providing a command-line interface for configuring the firewall. Verify that ufw is configured to allow traffic on any ports you need.
sudo apt-get install ufw
sudo ufw enable
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
Securing Nginx
The default distribution of Nginx doesn't enable SSL. To enable all the security features we require, we will build from source.
Download the source and install the build dependencies
# Install the build dependencies
sudo apt-get update
sudo apt-get install build-essential zlib1g-dev libpcre3-dev libssl-dev libxslt1-dev libxml2-dev libgd2-xpm-dev libgeoip-dev libgoogle-perftools-dev libperl-dev
# Download nginx 1.10.0 or latest
wget http://www.nginx.org/download/nginx-1.10.0.tar.gz
tar zxf nginx-1.10.0.tar.gz
Change the Nginx response name
Edit src/http/ngx_http_header_filter_module.c
static char ngx_http_server_string[] = "Server: Your Web Server" CRLF;
static char ngx_http_server_full_string[] = "Server: Your Web Server" CRLF;
Configure the options and build
The PCRE library is required for regular expressions. Regular expressions are used in the location directive for the ngx_http_rewrite_module. The http_ssl_module adds HTTPS protocol support.
Consider using a web application firewall like ModSecurity to harden your application.
./configure
--with-pcre=../pcre-8.38
--with-zlib=../zlib-1.2.8
--with-http_ssl_module
--with-stream
--with-mail=dynamic
Configure SSL
Configure your server to listen to HTTPS traffic on port
443by specifying a valid certificate issued by a trusted Certificate Authority (CA).Harden your security by employing some of the practices suggested below like choosing a stronger cipher and redirecting all traffic over HTTP to HTTPS.
Adding an
HTTP Strict-Transport-Security(HSTS) header ensures all subsequent requests made by the client are over HTTPS only.Do not add the Strict-Transport-Security header or chose an appropriate
max-ageif you plan to disable SSL in the future.
Add /etc/nginx/proxy.conf configuration file.
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffers 32 4k;
Edit /etc/nginx/nginx.conf configuration file. The example contains both http and server sections in one configuration file.
http {
include /etc/nginx/proxy.conf;
limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s;
server_tokens off;
sendfile on;
keepalive_timeout 29; # Adjust to the lowest possible value that makes sense for your use case.
client_body_timeout 10; client_header_timeout 10; send_timeout 10;
upstream hellomvc{
server localhost:5000;
}
server {
listen *:80;
add_header Strict-Transport-Security max-age=15768000;
return 301 https://$host$request_uri;
}
server {
listen *:443 ssl;
server_name example.com;
ssl_certificate /etc/ssl/certs/testCert.crt;
ssl_certificate_key /etc/ssl/certs/testCert.key;
ssl_protocols TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
ssl_ecdh_curve secp384r1;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling on; #ensure your cert is capable
ssl_stapling_verify on; #ensure your cert is capable
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
#Redirects all traffic
location / {
proxy_pass http://hellomvc;
limit_req zone=one burst=10;
}
}
}
Secure Nginx from clickjacking
Clickjacking is a malicious technique to collect an infected user's clicks. Clickjacking tricks the victim (visitor) into clicking on an infected site. Use X-FRAME-OPTIONS to secure your site.
Edit the nginx.conf file.
sudo nano /etc/nginx/nginx.conf
Add the the line add_header X-Frame-Options "SAMEORIGIN"; and save the file, then restart Nginx.
MIME-type sniffing
This header prevents Internet Explorer from MIME-sniffing a response away from the declared content-type as the header instructs the browser not to override the response content type. With the nosniff option, if the server says the content is text/html, the browser will render it as text/html.
Edit the nginx.conf file.
sudo nano /etc/nginx/nginx.conf
Add the the line add_header X-Content-Type-Options "nosniff" and save the file, then restart Nginx.
发布Asp.net core到nginx 使用nginx代理的更多相关文章
- docker 初识之二(简单发布ASP.NET Core 网站)
在发布ASP.NET Core网站以前,先介绍一下DaoCloud 一个免费的docker云容器服务平台.登陆官方网站,创建一台docker主机,这台主机有120分钟的使用时间,对于鄙人学习使用正好合 ...
- ubuntu下发布asp.net core并用nginx代理之旅
asp.net core 1.0.1发布已有些日子了,怀着好奇的心情体验了把ubuntu下的asp.net core 系统运行环境:ubuntu 16.0.4 for developer 首先搭建.n ...
- ASP.NET Core 缓存技术 及 Nginx 缓存配置
前言 在Asp.Net Core Nginx部署一文中,主要是讲述的如何利用Nginx来实现应用程序的部署,使用Nginx来部署主要有两大好处,第一是利用Nginx的负载均衡功能,第二是使用Nginx ...
- 微信小程序和asp.net core基于docker和nginx的交互
这个文章的题目起的比较长,我想实现这样一个产品: 前端是微信小程序,后端是基于docker运行的asp.net core webapi.webapi通过nginx实现的反向代理接入,nginx同样基于 ...
- 发布 ASP.NET Core 2.x 应用到 Ubuntu
简单绍一下如何将ASP.NET Core 应用发布到Linux (Ubuntu)服务器上,都是文档的东西. 服务器结构 ASP.NET Core 2.x 有两种server: HTTP.sys 只支持 ...
- 发布ASP.NET Core程序到Linux生产环境
原文翻译:Publish to a Linux Production Environment 作者:Sourabh Shirhatti 在这篇文章里我们将介绍如何在 Ubuntu 14.04 Serv ...
- 使用vs中的发布功能发布asp.net core项目时遇到ERROR_CERTIFICATE_VALIDATION_FAILED错误
今天将VS2015编制的一个asp.net core项目发布到服务器进行测试,使用的是vs中主菜单"生成"中的"发布"功能. 遇到了一个错误,在网上反复检索尝试 ...
- 重磅!!!微软发布ASP.NET Core 2.2,先睹为快。
我很高兴地宣布ASP.NET Core 2.2现在作为.NET Core 2.2的一部分提供! 如何获取? 您可以从.NET Core 2.2下载页面下载适用于您的开发机器和构建服务器的新.NET C ...
- docker 安装jenkins 发布 asp.net core 2.0
安装Docker 其实安装Docker的过程,大家可以到Docker官网找到自己相对应的安装文档进行安装,Docker区分CE和EE的两个版本,具体这两个版本有什么区别,大家自行查阅相关资料,这里不再 ...
随机推荐
- Elasticsearch cluster health: yellow unassigned shards
查看ES各个分片的状态 $ curl -XGET http://127.0.0.1:9200/_cluster/health?pretty { "cluster_name" : & ...
- 算法笔记_231:网格中移动字母(Java)
目录 1 问题描述 2 解决方案 1 问题描述 2x3=6个方格中放入ABCDE五个字母,右下角的那个格空着.如图[1.jpg]所示. 和空格子相邻的格子中的字母可以移动到空格中,比如,图中的C和 ...
- 算法笔记_202:第三届蓝桥杯软件类决赛真题(Java高职)
目录 1 填算式 2 提取子串 3 机器人行走 4 地址格式转换 5 排日程 前言:以下代码仅供参考,若有错误欢迎指正哦~ 1 填算式 [结果填空] (满分11分) 看这个算式: ☆☆☆ + ☆☆ ...
- Flash 加密和破解
关于Flash(swf),我们需要明确一点: ***Flash字节码的意义都是公开的 所以如果cracker真的有足够的耐心他最终还是可以破解掉你的Flash.我们能做的只是尽量提高Flash被破解的 ...
- Windows下安装Oracle Database 12c Release 1(12.1.0.2.0) - Enterprise Edition
Windows下安装Oracle Database 12c Release 1(12.1.0.2.0) 最近因需要在Oracle 数据库上建立ODI的资料档案库,需要安装Oracle Database ...
- Java HmacSHA1算法
Java HmacSHA1算法 public static String hmacSha1(String src, String key) { try { SecretKeySpec signingK ...
- Memcacher win7 安装测试
1.下载memcache 的windows 稳定版,解压放某个盘下面,比如在H:/wamp/www/php api/memcache: 2.在终端(即cmd 命令界面)下,输入安装命令 :H:/wam ...
- Effective前端(3)用CSS画一个三角形
来源:https://zhuanlan.zhihu.com/p/26160325 三角形的场景很常见,打开一个页面可以看到各种各样的三角形: 由于div一般是四边形,要画个三角形并不是那么直观.你可以 ...
- RHEL7 MariaDB测试
MariaDB安装及启动: yum groupinstall mariadb 启动mariadb systemctl restart mariadb systemctl enable mariadb ...
- Spark -14:spark Hadoop 高可用模式下读写hdfs
第一种,通过配置文件 val sc = new SparkContext() sc.hadoopConfiguration.set("fs.defaultFS", "hd ...