Installing ASP.NET Core 2.1 on Ubuntu 18.4 Linux
Before installing .NET, you’ll need to register the Microsoft key, register the product repository, and install required dependencies. This only needs to be done once per machine.
Open a command prompt and run the following commands:
Install the .NET Core 2.1 Runtime
This commands will install the .NET Core Hosting Bundle, which includes the .NET Core runtime and the ASP.NET Core runtime. To install just the .NET Core runtime, use the dotnet-runtime-2.1 package.
In your command prompt, run the following commands:
Install the .NET SDK
In your command prompt, run the following commands:
Notice: It is not necessary to install the .NET SDK on a productive server. You only need to install the SDK in the development environment.
Test the installation
To make sure it works after you’ve set it up, just run:
Create a new ASP.NET Core web application
Let’s create our first ASP.NET Core “hello world” web app. Just run:
The dotnet run command should start the webserver on a new open port (5001 for https and 5000 for http).
Now open your browser with the url you can see in the console output:
- For example: http://localhost:5000 or https://localhost:5001
- You should see a message like: Hello World!
Change the listening address via command line
The following command allows access to the kestrel webserver from anywhere. This parameter is useful to access the website from another host via docker or VirtualBox.
Please also check the current firewall status with sudo ufw status
Publish and copy over the app
Run dotnet publish from the development environment to package an app into a directory (for example, bin/Release/<target_framework_moniker>/publish ) that can run on the server:
Copy the ASP.NET Core app to the server using a tool that integrates into the organization’s workflow (for example, SCP, SFTP). It’s common to locate web apps under the var directory (for example, /var/aspnetcore/hellomvc ).
Note: In a production deployment scenario, a continuous integration workflow does the work of publishing the app and copying the assets to the server.
How to host ASP.NET Core on Linux using Nginx?
In my previous article, I have shared my experience on hosting MongoDB server on AWS EC2 Instance. The EC2 instance is running on Ubuntu Server 16.04 LTS machine. To get some knowledge on how to make EC2 instance up and running, you can check this article.
Today, I will share my experience on how to host ASP.NET Core Web API application in my EC2 instance. So, let’s get started.
Step 1: Installing .NET Core in Linux
You will have to install dependencies needed to develop .NET Core applications on Linux. But, there are different dependencies for different Linux distributions/versions. You can check this article for what dependencies should you install for which Linux distributions/versions.
At first, let’s go to the AWS EC2 dashboard and grab the Public IPV4 address like below:
Let’s open PuTTY and connect to the EC2 instance using the copied IPV4 address and login to the EC2 instance.
Now, before installing the dependencies, you should first check which .net core version you are using in your application. You can check by running below command in the console of machine where you are building your application.
Our version is 2.1.200. Keep that in mind because you will install this version in the instance.
Step 1.1: Register Microsoft key and feed
Before installing .NET, you’ll need to register the Microsoft key, register the product repository, and install required dependencies. This only needs to be done once per machine.
Open a command prompt and run the following commands:
Step 1.2: Install .NET Core SDK
You need to update the products available for installation, then install the .NET SDK. In your command prompt, run the following commands:
You can see that we have installed the same .net core sdk version in our EC2 instance also. To check whether it has been installed properly or not, run below command in the Ubuntu console:
Step 2: Host ASP.NET Core on Linux with Nginx
Now, we have to copy our application over to the Linux. Before that, to copy our application code, we need to install WinSCP.
WinSCP is a popular SFTP client and FTP client for Microsoft Windows. It is used to copy file between a local computer and remote servers using FTP, FTPS, SCP, SFTP, WebDAV or S3 file transfer protocols.
Now, let’s connet our EC2 instance with WinSCP like below:
We need to paste our EC2 instance IPV4 address in the Host Name section. So, after connecting successfully, we can see below screen:
On the left is my local computer files and on the right is home directory of my remote computer means the files of the EC2 instance. Now, let’s create a directory in my remote computer called CoreRESTServer.
Now, let’s go to our application code and go to the directory where the application main solution .sln file resides. And, let’s open the command prompt here and run the below command to publish:
You will see some files are generated inside the awssite directory. Now, we will copy all the files of awssite directory of our local computer to the CoreRESTServer directory of remote computer like below:
Now, we have to configure a reverse proxy server in our remote machine.
A reverse proxy is a common setup for serving dynamic web apps. A reverse proxy terminates the HTTP request and forwards it to the ASP.NET Core app.
Kestrel is great for serving dynamic content from ASP.NET Core. However, the web serving capabilities aren’t as feature rich as servers such as IIS, Apache, or Nginx. A reverse proxy server can offload work such as serving static content, caching requests, compressing requests, and SSL termination from the HTTP server. A reverse proxy server may reside on a dedicated machine or may be deployed alongside an HTTP server.
Step 2.1: Install Nginx
We will use apt-get to install Nginx. The installer creates a systemd init script that runs Nginx as daemon on system startup. We will run the below command:
Since Nginx was installed for the first time, we have to explicitly start it by running:
We can verify whether browser displays the default landing page for Nginx. The landing page is reachable at http://<server_IP_address>/index.nginx-debian.html . As our server_IP_adress is 52.221.213.34, so we can see a landing page at http://52.221.213.34/index.nginx-debian.html .
Step 2.2: Configue Nginx
To configure Nginx as a reverse proxy to forward requests to our ASP.NET Core app, we need to modify /etc/nginx/sites-available/default. Let’s open it in a text editor, and replace the contents with the following:
You can see the server is listening to port 80. We need to enable this port in the security group. You can see this article on how to add rule in the security group. Since we have All traffic enabled, we don’t need to enable TCP at port 80 again. It is already enabled in the security group. But, we can also enable the TCP port 80 only rather than opening all the traffic.
Once the Nginx configuration is established, we have to run sudo nginx -t to verify the syntax of the configuration files. If the configuration file test is successful, we will force Nginx to pick up the changes by running sudo nginx -s reload .
Now, to directly run the app on the server:
- We have to navigate to the app’s directory means to CoreRESTServer directory.
- Then, we have to run the app’s executable: dotnet <app_executable> like
If a permissions error occurs, we have to change the permissions of the file:
If the app runs on the server but fails to respond over the Internet, we have to check the server’s firewall and confirm that port 80 is open.
Now, our server is setup to forward requests made to http://52.221.213.34:80 on to the ASP.NET Core app running on Kestrel at http://127.0.0.1:5000.
Step 2.3: Running our application as a service
But, if we close the PuTTY session, our application will stop. But, we don’t want that. We have to use systemd to 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.
At first, we will create a service file for our web application.
Then, inside that my-web-api.service file, i have included below configurations:
Then, we need to enable the service and run it.
Now, the status command should show the service as running if the configuration is correct. So, our web application is running. Kestrel by default listens on port 5000, so our application is available on http://localhost:5000.
Now, if we close the PuTTY session, our web application is still running.
So, we have successfully host our .net core web application Linux using Nginx.
Развертывание ASP.NET Core MVC приложения на Ubuntu 20.04 на VPS. Установка SSL
MS SQL требует минимум 2GB свободной оперативной памяти для установки и запуска.
Показывать я буду на примере готового ASP.NET Core сайта для просмотра аниме (японская анимация). Оно работает и запускается без ошибок на localhost. Приложение использует MS SQL базу данных, которую мы установим и настроим на Шаге шесть.
ASP.NET Core 3.1 Application | MS SQL
Шаг первый: публикация приложения
В обозревателе решений нажмите правой кнопкой мыши по проекту -> опубликовать.
Если у вас нет профиля, нажмите «Добавить профиль публикации» -> Целевой объект выбираем папка -> Указываем удобно место, куда файлы выгрузятся -> Готово.
Мои настройки профиля:
Целевая платформа: net6.0
Режим развертывания: Зависит от платформы
Целевая среда выполнения: Переносимая версия
Если у вас другая целевая платформа, то на Шаге три вам нужно будет скачать версию .NET-SDK, которая вам нужна.
Шаг второй: отправить файлы через SFTP и установить SSH соединение
Имя пользователя и пароль пришли мне на e-mail, указанный при регистрации. Обычно имя пользователя стоит root. IP адрес написан в настройках VPS на сайте.
Чтобы подключиться по SFTP (SSH File Transfer Protocol) для передачи файлов, я использую программу FileZilla.
Запускаю -> Файл -> Менеджер сайтов -> Новый сайт
Протокол надо выбрать SFTP — SSH File Transfer Protocol.
Хост — это IP от VPS.
Логин и пароль ввожу из письма, нажимаю соединиться.
На VPS я создал директорию /var/netcore/ и файлы опубликованного приложения, при помощи Drag&Drop перенес в созданную директорию. FileZilla в логах показывает какие-то ошибки, но я их просто игнорирую, и все работает.
Установка SSH соединения. Большинство сайтов предоставляют возможность открыть консоль с SSH прямо в браузере нажатием одной кнопки, но он какой-то лагучий. Сделать это через CMD на windows 10 мне на много удобнее.
Шаг третий: установить .NET 6.0 на Ubuntu
У меня не было репозиториев Microsoft с .NET-SDK 6.0, поэтому я установил их командами:
Я устанавливаю .NET 6.0 и необходимые библиотеки:
Шаг четвертый: установить и настроить Nginx
Следующие, что надо сделать — это настроить файл конфигурации, который будет перенаправлять запросы по порту 80 (а в будущем и 443 для SSL) на наше ASP.NET Core приложение. Файл конфигурации находится по пути /etc/nginx/sites-available/default
Можете создать файл на вашей ОС и при помощи FileZilla перенести его, или создать его при помощи текстового редактора nano/vim. Я воспользуюсь nano.
Если ваше .NET приложение запущено на другом порте, указывайте его вместо 5000.
Проверяем конфиг на ошибки и перезапускаем nginx, чтобы обновить конфиг:
Шаг пятый: создать сервис с ASP.NET Core приложением
По сути этот шаг необязательный и его можно просто пропустить, заменив командой dotnet YourApp.dll . Теперь вы можете в строке браузера написать IP адрес VPS и увидеть ваш сайт. У меня сейчас ошибка 500 из-за отсутствия MS SQL на VPS, исправив ее на Шаге шесть, сайт будет работать. Но держать в потоке (я не уверен, как это в unix называется) вашего пользователя всегда запущенное приложения — это не вариант, поэтому давайте настроим сервис, который будет делать это постоянно на фоне.
Чтобы завершить выполнение приложения, нажмите сочетание клавиш Ctrl + C.
Я создал файл по пути /etc/systemd/system/AspNetServer.service AspNetServer — это имя нашего сервиса, позже мы будем его использовать, чтобы запускать, останавливать, перезапускать приложение, читать его журналы и т.д. Можете указать любое имя, главное оставьте .service в конце.
Кому проще создать файл на своей ОС и отправить его через FileZilla, делайте так, я же просто воспользуюсь командой sudo nano /etc/systemd/system/AspNetServer.service и вставлю следующий код:
На 5 строчке вместо AnimeSite.dll укажите dll файл вашего приложения.
Теперь запустим сервер:
Проверить статус сервиса можно командой:
Чтобы выйти из режима просмотра статуса, нажмите Ctrl + C.
Если ваше приложение не использует базы данных, то все готово, введите IP от VDS в строку браузера и проверяйте. Если приложение выдает ошибку или вы просто хотите почитать вывод приложения, используйте команду:
При помощи ввода цифр можете выбрать, на какую строчку перескочить. Я пишу 9999, чтобы перейти в конец и посмотреть, какое исключение появляется.
Шаг шестой: установка и настройка MS SQL
Установим необходимую библиотеку и репозитории MS SQL:
Затем установим загрузчик MS SQL:
И при помощи этой команды перейдем к установке MS SQL:
Нам предлагают выбрать, какую версию установить, я выберу Express под номером 3. Соглашаюсь с условиями пользования, устанавливаю свой супер сложный пароль и готово. Проверим, работает ли MS SQL командой systemctl status mssql-server —no-pager
Я изменяю строку подключения в appsettings.json, указав свой супер сложный пароль:
Важно! Как верно отметили в комментариях, подключаться к БД через sa не правильно. Лучше создайте пользователя и выделите ему минимальные необходимые права.
И перезапускаю сервис AspNetServer командой:
Готово! Сайт работает. Следующий шаг будет посвящен настройке SSL сертификата.
Шаг седьмой: настройка SSL сертификата
При покупке домена мне в подарок дали SSL сертификат. На почту пришли все данные. Чтобы установить его на сайт я создал 2 файла:
certificate.crt — сам сертификат
private.key — приватный ключ
Важно! Данные в эти файлы надо вставлять вместе с
——BEGIN CERTIFICATE——
——END CERTIFICATE——
В директории с ASP.NET Core приложением я создал директорию ssl-certificates и перенес все файлы сертификатов по пути /var/netcore/ssl-certificates/
Теперь надо изменить файл конфигурации Nginx, я открываю редактор nano командой sudo nano /etc/nginx/sites-available/default и изменяю код:
Если хотите, чтобы HTTP автоматический перенаправлялся на HTTPS, измените содержимое server, где listen 80 на это:
Name already in use
AspNetCore.Docs / aspnetcore / host-and-deploy / linux-nginx.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Host ASP.NET Core on Linux with Nginx
. moniker range=»>= aspnetcore-6.0″ This guide explains setting up a production-ready ASP.NET Core environment for Ubuntu, Red Hat Enterprise (RHEL), and SUSE Linux Enterprise Server.
For information on other Linux distributions supported by ASP.NET Core, see Prerequisites for .NET Core on Linux.
- Places an existing ASP.NET Core app behind a reverse proxy server.
- Sets up the reverse proxy server to forward requests to the Kestrel web server.
- Ensures the web app runs on startup as a daemon.
- Configures a process management tool to help restart the web app.
- Access to Ubuntu 20.04 with a standard user account with sudo privilege.
- The latest stable .NET runtime installed on the server.
- An existing ASP.NET Core app.
- Access to Red Hat Enterprise (RHEL) 8.0 or later with a standard user account with sudo privilege.
- The latest stable .NET runtime installed on the server.
- An existing ASP.NET Core app.
- Access to SLES 12 or 15 with a standard user account with sudo privilege.
- The latest stable .NET runtime installed on the server.
- An existing ASP.NET Core app.
At any point in the future after upgrading the shared framework, restart the ASP.NET Core apps hosted by the server.
Publish and copy over the app
If the app is run locally in the Development environment and isn’t configured by the server to make secure HTTPS connections, adopt either of the following approaches:
Configure the app to handle secure local connections. For more information, see the HTTPS configuration section.
Configure the app to run at the insecure endpoint:
Deactivate HTTPS Redirection Middleware in the Development environment ( Program.cs ):
For more information, see xref:fundamentals/environments#configure-services-and-middleware-by-environment.
Remove https://localhost:5001 (if present) from the applicationUrl property in the Properties/launchSettings.json file.
For more information on configuration by environment, see xref:fundamentals/environments.
Run dotnet publish from the development environment to package an app into a directory (for example, bin/Release/
The app can also be published as a self-contained deployment if you prefer not to maintain the .NET Core runtime on the server.
Copy the ASP.NET Core app to the server using a tool that integrates into the organization’s workflow (for example, SCP , SFTP ). It’s common to locate web apps under the var directory (for example, var/www/helloapp ).
[!NOTE] Under a production deployment scenario, a continuous integration workflow does the work of publishing the app and copying the assets to the server.
- From the command line, run the app: dotnet <app_assembly>.dll .
- In a browser, navigate to http://<serveraddress>:<port> to verify the app works on Linux locally.
Configure a reverse proxy server
A reverse proxy is a common setup for serving dynamic web apps. A reverse proxy terminates the HTTP request and forwards it to the ASP.NET Core app.
Use a reverse proxy server
Kestrel is great for serving dynamic content from ASP.NET Core. However, the web serving capabilities aren’t as feature rich as servers such as IIS, Apache, or Nginx. A reverse proxy server can offload work such as serving static content, caching requests, compressing requests, and HTTPS termination from the HTTP server. A reverse proxy server may reside on a dedicated machine or may be deployed alongside an HTTP server.
For the purposes of this guide, a single instance of Nginx is used. It runs on the same server, alongside the HTTP server. Based on requirements, a different setup may be chosen.
Because requests are forwarded by reverse proxy, use the Forwarded Headers Middleware from the Microsoft.AspNetCore.HttpOverrides package. The middleware updates the Request.Scheme , using the X-Forwarded-Proto header, so that redirect URIs and other security policies work correctly.
Invoke the xref:Microsoft.AspNetCore.Builder.ForwardedHeadersExtensions.UseForwardedHeaders%2A method before calling other middleware. Configure the middleware to forward the X-Forwarded-For and X-Forwarded-Proto headers:
. code language=»csharp» source=»
If no xref:Microsoft.AspNetCore.Builder.ForwardedHeadersOptions are specified to the middleware, the default headers to forward are None .
Proxies running on loopback addresses ( 127.0.0.0/8 , [::1] ), including the standard localhost address ( 127.0.0.1 ), are trusted by default. If other trusted proxies or networks within the organization handle requests between the internet and the web server, add them to the list of xref:Microsoft.AspNetCore.Builder.ForwardedHeadersOptions.KnownProxies%2A or xref:Microsoft.AspNetCore.Builder.ForwardedHeadersOptions.KnownNetworks%2A with xref:Microsoft.AspNetCore.Builder.ForwardedHeadersOptions. The following example adds a trusted proxy server at IP address 10.0.0.100 to the Forwarded Headers Middleware KnownProxies :
. code language=»csharp» source=»
For more information, see xref:host-and-deploy/proxy-load-balancer.
Use apt-get to install Nginx. The installer creates a systemd init script that runs Nginx as daemon on system startup. Follow the installation instructions for Ubuntu at Nginx: Official Debian/Ubuntu packages.
Use yum-utils to select and install an Nginx module stream. Follow the installation instructions for RHEL at Nginx: Linux packages — RHEL.
Use yum-utils to select and install an Nginx module stream. Follow the installation instructions for SLES at Nginx: Linux packages — SLES.
[!NOTE] If optional Nginx modules are required, building Nginx from source might be required.
Since Nginx was installed for the first time, explicitly start it by running:
Verify a browser displays the default landing page for Nginx. The landing page is reachable at http://<server_IP_address>/index.nginx-debian.html .
To configure Nginx as a reverse proxy to forward HTTP requests to your ASP.NET Core app, modify /etc/nginx/sites-available/default . Open it in a text editor, and replace the contents with the following snippet:
To configure Nginx as a reverse proxy to forward HTTP requests to an ASP.NET Core app, modify /etc/nginx.conf . Replace the server<> code block with the following snippet:
To configure Nginx as a reverse proxy to forward HTTP requests to an ASP.NET Core app, modify /etc/nginx.conf . Replace the server<> code block with the following snippet:
If the app is a SignalR or Blazor Server app, see xref:signalr/scale#linux-with-nginx and xref:blazor/host-and-deploy/server#linux-with-nginx respectively for more information.
When no server_name matches, Nginx uses the default server. If no default server is defined, the first server in the configuration file is the default server. As a best practice, add a specific default server that returns a status code of 444 in your configuration file. A default server configuration example is:
With the preceding configuration file and default server, Nginx accepts public traffic on port 80 with host header example.com or *.example.com . Requests not matching these hosts won’t get forwarded to Kestrel. Nginx forwards the matching requests to Kestrel at http://127.0.0.1:5000 . For more information, see How nginx processes a request. To change Kestrel’s IP/port, see Kestrel: Endpoint configuration.
[!WARNING] Failure to specify a proper server_name directive exposes your app to security vulnerabilities. Subdomain wildcard binding (for example, *.example.com ) doesn’t pose this security risk if you control the entire parent domain (as opposed to *.com , which is vulnerable). For more information, see RFC 9110: HTTP Semantics (Section 7.2: Host and :authority).
Once the Nginx configuration is established, run sudo nginx -t to verify the syntax of the configuration files. If the configuration file test is successful, force Nginx to pick up the changes by running sudo nginx -s reload .
To directly run the app on the server:
- Navigate to the app’s directory.
- Run the app: dotnet <app_assembly.dll> , where app_assembly.dll is the assembly file name of the app.
If the app runs on the server but fails to respond over the internet, check the server’s firewall and confirm port 80 is open. If using an Azure Ubuntu VM, add a Network Security Group (NSG) rule that enables inbound port 80 traffic. There’s no need to enable an outbound port 80 rule, as the outbound traffic is automatically granted when the inbound rule is enabled.
If the app runs on the server but fails to respond over the internet, check the server’s firewall and confirm port 80 is open.
If the app runs on the server but fails to respond over the internet, check the server’s firewall and confirm port 80 is open.
When done testing the app, shut down the app with Ctrl + C (Windows) or ⌘ + C (macOS) at the command prompt.
Monitor the app
The server is set up to forward requests made to http://<serveraddress>:80 on to the ASP.NET Core app running on Kestrel at http://127.0.0.1:5000 . However, Nginx isn’t set up to manage the Kestrel process. systemd can be used to 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:
The following example is an .ini service file for the app:
In the preceding example, the user that manages the service is specified by the User option. The user ( www-data ) must exist and have proper ownership of the app’s files.
Use TimeoutStopSec to configure the duration of time to wait for the app to shut down after it receives the initial interrupt signal. If the app doesn’t shut down in this period, SIGKILL is issued to terminate the app. Provide the value as unitless seconds (for example, 150 ), a time span value (for example, 2min 30s ), or infinity to disable the timeout. TimeoutStopSec defaults to the value of DefaultTimeoutStopSec in the manager configuration file ( systemd-system.conf , system.conf.d , systemd-user.conf , user.conf.d ). The default timeout for most distributions is 90 seconds.
Linux has a case-sensitive file system. Setting ASPNETCORE_ENVIRONMENT to Production results in searching for the configuration file appsettings.Production.json , not appsettings.production.json .
Some values (for example, SQL connection strings) must be escaped for the configuration providers to read the environment variables. Use the following command to generate a properly escaped value for use in the configuration file:
Colon ( : ) separators aren’t supported in environment variable names. Use a double underscore ( __ ) in place of a colon. The Environment Variables configuration provider converts double-underscores into colons when environment variables are read into configuration. In the following example, the connection string key ConnectionStrings:DefaultConnection is set into the service definition file as ConnectionStrings__DefaultConnection :
Save the file and enable the service.
Start the service and verify that it’s running.
With the reverse proxy configured and Kestrel managed through systemd , the web app is fully configured and can be accessed from a browser on the local machine at http://localhost . It’s also accessible from a remote machine, barring any firewall that might be blocking. Inspecting the response headers, the Server header shows the ASP.NET Core app being served by Kestrel.
Since the web app 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-helloapp.service -specific items, use the following command:
For further filtering, time options such as —since today , —until 1 hour ago , or a combination of these can reduce the number of entries returned.
The ASP.NET Core Data Protection stack is used by several ASP.NET Core middlewares, including authentication middleware (for example, cookie middleware) and cross-site request forgery (CSRF) protections. Even if Data Protection APIs aren’t called by user code, data protection should be configured to create a persistent cryptographic key store. If data protection isn’t configured, the keys are held in memory and discarded when the app restarts.
If the key ring is stored in memory when the app restarts:
- All cookie-based authentication tokens are invalidated.
- Users are required to sign in again on their next request.
- Any data protected with the key ring can no longer be decrypted. This may include CSRF tokens and ASP.NET Core MVC TempData cookies.
To configure data protection to persist and encrypt the key ring, see:
- xref:security/data-protection/implementation/key-storage-providers
- xref:security/data-protection/implementation/key-encryption-at-rest
Long request header fields
Proxy server default settings typically limit request header fields to 4 K or 8 K depending on the platform. An app may require fields longer than the default (for example, apps that use Azure Active Directory). If longer fields are required, the proxy server’s default settings require adjustment. The values to apply depend on the scenario. For more information, see your server’s documentation.
[!WARNING] Don’t increase the default values of proxy buffers unless necessary. Increasing these values increases the risk of buffer overrun (overflow) and Denial of Service (DoS) attacks by malicious users.
Linux Security Modules (LSM) is a framework that’s part of the Linux kernel since Linux 2.6. LSM supports different implementations of security modules. AppArmor is an LSM that implements a Mandatory Access Control system, which allows confining the program to a limited set of resources. Ensure AppArmor is enabled and properly configured.
Configure the firewall
Close off all external ports that aren’t in use. Uncomplicated firewall (ufw) provides a front end for iptables by providing a CLI for configuring the firewall.
[!WARNING] A firewall prevents access to the whole system if not configured correctly. Failure to specify the correct SSH port effectively locks you out of the system if you are using SSH to connect to it. The default port is 22. For more information, see the introduction to ufw and the manual.
Install ufw and configure it to allow traffic on any ports needed.
[!WARNING] A firewall prevents access to the whole system if not configured correctly. Failure to specify the correct SSH port effectively locks you out of the system if you are using SSH to connect to it. The default port is 22. For more information, see the introduction to ufw.
Install ufw and configure it to allow traffic on any ports needed.
[!WARNING] A firewall prevents access to the whole system if not configured correctly. Failure to specify the correct SSH port effectively locks you out of the system if you are using SSH to connect to it. The default port is 22. For more information, see the introduction to ufw.
Install ufw and configure it to allow traffic on any ports needed.
Change the Nginx response name
Configure the server with additional required modules. Consider using a web app firewall, such as ModSecurity, to harden the app.
Configure the app for secure (HTTPS) local connections
The dotnet run command uses the app’s Properties/launchSettings.json file, which configures the app to listen on the URLs provided by the applicationUrl property. For example, https://localhost:5001;http://localhost:5000 .
Configure the app to use a certificate in development for the dotnet run command or development environment ( F5 or Ctrl + F5 in Visual Studio Code) using one of the following approaches:
- Replace the default certificate from configuration (Recommended)
- KestrelServerOptions.ConfigureHttpsDefaults
Configure the reverse proxy for secure (HTTPS) client connections
-
(Nginx documentation)
Configure the server to listen to HTTPS traffic on port 443 by specifying a valid certificate issued by a trusted Certificate Authority (CA).
Harden the security by employing some of the practices depicted in the following /etc/nginx/nginx.conf file.
The following example doesn’t configure the server to redirect insecure requests. We recommend using HTTPS Redirection Middleware. For more information, see xref:security/enforcing-ssl.
[!NOTE] For development environments where the server configuration handles secure redirection instead of HTTPS Redirection Middleware, we recommend using temporary redirects (302) rather than permanent redirects (301). Link caching can cause unstable behavior in development environments.
Adding a Strict-Transport-Security (HSTS) header ensures all subsequent requests made by the client are over HTTPS. For guidance on setting the Strict-Transport-Security header, see xref:security/enforcing-ssl#http-strict-transport-security-protocol-hsts.
If HTTPS will be disabled in the future, use one of the following approaches:
- Don’t add the HSTS header.
- Choose a short max-age value.
Add the /etc/nginx/proxy.conf configuration file:
Replace the contents of the /etc/nginx/nginx.conf configuration file with the following file. The example contains both http and server sections in one configuration file.
Modify /etc/nginx/nginx.conf . Open it in a text editor, and replace the http<> and server<> code blocks with contents with the following snippet:
Modify /etc/nginx/nginx.conf . Open it in a text editor, and replace the http<> and server<> code blocks with contents with the following snippet:
[!NOTE] Blazor WebAssembly apps require a larger burst parameter value to accommodate the larger number of requests made by an app. For more information, see xref:blazor/host-and-deploy/webassembly#nginx.
- ssl_stapling
- ssl_stapling_file
- ssl_stapling_responder
- ssl_stapling_verify
Secure Nginx from clickjacking
Clickjacking, also known as a UI redress attack, is a malicious attack where a website visitor is tricked into clicking a link or button on a different page than they’re currently visiting. Use X-FRAME-OPTIONS to secure the site.
To mitigate clickjacking attacks:
Edit the nginx.conf file:
Within the http<> code block, add the line: add_header X-Frame-Options «SAMEORIGIN»;
This header prevents most browsers 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 renders it as text/html .
Edit the nginx.conf file:
Within the http<> code block, add the line: add_header X-Content-Type-Options «nosniff»;