Linux nginx сменить порт

How to start nginx via different port(other than 80)

Hi I am a newbie on nginx, I tried to set it up on my server(running Ubuntu 4), which already has apache running. So after I apt-get install it, I tried to start nginx. Then I get the message like this:

Starting nginx: the configuration file /etc/nginx/nginx.conf syntax is ok configuration file /etc/nginx/nginx.conf test is successful [emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use) [emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use) [emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use) [emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use) [emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use) 

That makes sense as Apache is using port 80. Then I tried to modify nginx.conf , I reference some articles, so I changed it like so:

After saving this and try to start nginx again, I still get the same error as previously. I cannot really find a related post about this, could any good people shred some light? I should post all the content in conf here:

user www-data; worker_processes 1; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid; events < worker_connections 1024; # multi_accept on; >http < include /etc/nginx/mime.types; access_log /var/log/nginx/access.log; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; tcp_nodelay on; gzip on; gzip_disable "MSIE 1\.(. *SV1)"; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; server < listen 81; location / < proxy_pass http://94.143.9.34:9500; proxy_set_header Host $host:81; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Via "nginx"; >> > mail < See sample authentication script at: http://wiki.nginx.org/NginxImapAuthenticateWithApachePhpScript auth_http localhost/auth.php; pop3_capabilities "TOP" "USER"; imap_capabilities "IMAP4rev1" "UIDPLUS"; server < listen localhost:110; protocol pop3; proxy on; >server < listen localhost:143; protocol imap; proxy on; >> 

Источник

Как изменить порт Nginx в Linux

Nginx — это стабильный сервер с открытым исходным кодом, на котором сегодня работают одни из самых посещаемых веб-сайтов в Интернете. Среди веб-сервисов веб-сервер Nginx можно успешно развернуть в качестве балансировщика нагрузки, обратного веб-прокси или прокси-сервера POP и IMAP.

По умолчанию сервер Nginx HTTP прослушивает входящие соединения и привязывается к порту 80, который представляет собой стандартный веб-порт. Однако конфигурация TLS, которая по умолчанию не включена в Nginx, прослушивает безопасные соединения через порт 443.

Чтобы заставить HTTP-сервер Nginx прослушивать входящие веб-соединения через другие нестандартные порты, нам нужно отредактировать основной файл конфигурации и изменить или добавить новый оператор, отражающий этот факт.

В системе на основе Ubuntu и Debian нам необходимо изменить файл /etc/nginx/sites-enabled/default и на RHEL и дистрибутивы на базе CentOS отредактируйте файл /etc/nginx/nginx.conf.

Для начала откройте файл конфигурации Nginx в текстовом редакторе и измените номер порта, как показано в приведенном ниже отрывке.

# vi /etc/nginx/sites-enabled/default [On Debian/Ubuntu] # vi /etc/nginx/nginx.conf [On CentOS/RHEL]

В этом отрывке мы настроим HTTP-сервер Nginx для прослушивания входящих соединений через порт 3200. Найдите строку, которая начинается с оператора listen в директиве сервера, и измените порт с 80 на 3200, как показано на рисунке ниже.

listen 3200 default_server;

После изменения оператора порта Nginx вам необходимо перезапустить веб-сервер, чтобы выполнить привязку к новому порту в дистрибутивах Linux на базе Debian. Проверьте таблицу сокетов локальной сети с помощью команды netstat или ss. Порт 3200 должен отображаться в таблице локальной сети вашего сервера.

# systemctl restart nginx # netstat -tlpn| grep nginx # ss -tlpn| grep nginx

В дистрибутиве Linux на основе CentOS или RHEL вам необходимо установить пакет policycoreutils и добавить приведенные ниже правила, требуемые SELinux для привязки Nginx к новому порту. .

# yum install policycoreutils # semanage port -a -t http_port_t -p tcp 3200 # semanage port -m -t http_port_t -p tcp 3200

Наконец, перезапустите HTTP-сервер Nginx, чтобы изменения вступили в силу.

# systemctl restart nginx.service

Проверьте прослушивающие сокеты сетевых таблиц.

# netstat -tlpn| grep nginx # ss -tlpn| grep nginx

Чтобы проверить, доступен ли веб-сервер с компьютеров в вашей сети, откройте браузер и перейдите к IP-адресу вашего сервера или доменному имени через порт 3200. Вы должны увидеть веб-страницу Nginx по умолчанию, как показано на снимке экрана ниже.

Читайте также:  Welcome to My Website!

Однако, если вы не можете просмотреть веб-страницу Nginx, вернитесь к консоли сервера и проверьте правила брандмауэра, чтобы разрешить входящий трафик через порт 3200/tcp.

Источник

How to Change Nginx Port in Linux

Nginx is an open source stable server that powers some of the most high traffic websites in internet today. Among web services, Nginx web server can be successfully deployed as an load-balancer, web reverse proxy or as a POP and IMAP proxy server.

By default, Nginx HTTP server listens for incoming connection and binds on port 80, which represents the standard web port. However, the TLS configuration, which is not enabled by default in Nginx, listens for secure connections on port 443.

In order to make Nginx HTTP server to listen for incoming web connections on other non-standard ports, we need to edit the main configuration file and change or add a new statement to reflect this fact.

In Ubuntu and Debian based system, we need to modify the /etc/nginx/sites-enabled/default file and on RHEL and CentOS based distributions edit /etc/nginx/nginx.conf file.

To begin with, open Nginx configuration file with a text editor, and change the port number as shown in the below excerpt.

# vi /etc/nginx/sites-enabled/default [On Debian/Ubuntu] # vi /etc/nginx/nginx.conf [On CentOS/RHEL]

In this excerpt we’ll configure Nginx HTTP server to listen for incoming connections on port 3200. Search for the line that begins with listen statement in server directive and change the port from 80 to 3200, as illustrated in the below image.

listen 3200 default_server;

Change Nginx Port in Ubuntu Change Nginx Port in CentOS

After altering Nginx port statement, you need to restart the web server in order to bind on the new port on Debian based Linux distributions. Verify local network sockets table with netstat or ss command. Port 3200 should be displayed in your server local network table.

# systemctl restart nginx # netstat -tlpn| grep nginx # ss -tlpn| grep nginx

In CentOS or RHEL based Linux distribution you need to install policycoreutils package and add the below rules required by SELinux for Nginx to bind on the new port.

# yum install policycoreutils # semanage port -a -t http_port_t -p tcp 3200 # semanage port -m -t http_port_t -p tcp 3200

Finally restart Nginx HTTP server to apply changes.

# systemctl restart nginx.service

Check network tables listening sockets.

# netstat -tlpn| grep nginx # ss -tlpn| grep nginx

Verify Nginx New Port

To check if the web server can be accessed form computers in your network, open a browser and navigate to your server IP address or domain name on port 3200. You should see Nginx default web page, as illustrated in the below screenshot.

Читайте также:  Astra linux выключить parsec

Nginx Default Page

However, if you can’t browse Nginx web page, return to server console and check the firewall rules to allow incoming traffic on port 3200/tcp.

Источник

How to Change Nginx Port on Ubuntu Linux

Nginx, probably the second most popular HTTP server in use today, is easy to manage and configure. Nginx is a lightweight and efficient HTTP server but can be served as a proxy server and more.

Sometimes you’ll want Nginx to listen and communicate over not its default port but a different port instead. The steps below can be a good starting point when you want to do that.

For example, if you want the Nginx HTTP server to sit behind a proxy server, then the proxy server must be configured to listen on the default port 80. In this case, Nginx must also be configured to listen on a different port than 80 since two services can’t be assigned one port to listen on. There would be contentions.

This tutorial will show students and new users how to quickly switch the Nginx default port from 80 to something else. Like 8082. in this way, other services can use port 80 to communicate.

When you’re ready to make this change, continue below:

Identifying Nginx Port Config File

To change the Nginx default port number, you need to look in a single directory, unlike Apache2. This is Nginx default virtual hosts directory /etc/nginx/sites-available. This directory is where you’ll find individual virtual host configuration files.

Each file contains a port for Nginx to listen and communicate. You’ll do it in each virtual host file if you want to change the Nginx port.

Below is the location to can change the Nginx default port numbers

sudo nano /etc/nginx/sites-available/default

Changing Nginx Port Number

Now that you’ve identified the files, you can change the Nginx port number and continue below to make those changes. For this post, we’ll change the default ports 80 to 8082 and 443 to 444.

First, run the commands below to open the port—conf file.

sudo nano /etc/nginx/sites-available/default

Then change the Listen line from 80 to 8082

server < listen 8082 default_server; listen [::]:8082 default_server; listen [::]:444 ssl; ssl_certificate /path_to_cert_file; ssl_certificate_key /path_to_cert_key_file; root /var/www/html; index index.php index.html index.htm; server_name _; location / < try_files $uri $uri/ =404; >. .

Restart Nginx

Now that you’ve changed the port number in all the files, run the commands below to restart Nginx.

sudo systemctl restart nginx.service

After that, the Nginx service will listen to the port you assigned above.

That’s it! This is how one changes Nginx port numbers.

You may also like the post below:

Richard W

I love computers; maybe way too much. What I learned I try to share at geekrewind.com.

Источник

How to Change Nginx 80 Port in Linux

Nginx is an open-source lightweight web server alternative to apache to handle high-traffic websites.

With all its due features, it can easily manage to load balance and reverse proxy for your site or can be used as a mail server proxy as a POP and IMAP.

By default, Nginx runs on port 80 to handle web traffic requests, which can be changed to something else by editing the configuration files.

Читайте также:  Linux file permissions denied

Today, you will learn how to change the Nginx port in Linux in a few simple steps.

Prerequisites

  • Nginx Web Server in your system
  • Web Browser to check the result (Chrome, Firefox, etc.)
  • Your 2-minute time

How to Install Nginx in Linux (Skip if it exists)

To install the Nginx web server for your Debian or RHEL-based distributions, ensure you have a proper internet connection and open your terminal using Ctrl+Alt+t or Ctl+Shift+t and execute the below command.

Note : Installation requires system changes, having a root user or sudo account should be a must to gain the privileges.

$ sudo apt install nginx [On Debian/Ubuntu] $ sudo dnf install nginx [On CentOS/Fedora]

After the installation process is complete, start the server daemon process using the below command.

$ sudo systemctl start nginx

As you have installed Nginx in your respective Linux system, you can jump to the next step to continue changing the Nginx port in Linux.

Modifying the Configuration Files

Changing the default Nginx port requires modifications in the configuration files. This configuration file location might differ from distribution to distribution.

For Debian/Ubuntu distributions, the Nginx Web Server configuration file required to be modified is located at /etc/nginx/sites-enabled/default

For CentOS/Fedora distributions, the Nginx Web Server configuration file required to be modified is located at /etc/nginx/nginx.conf

Change Nginx Port in Linux

Before starting the process of changing the default port, stop your currently running server using the below command.

$ sudo systemctl stop nginx

Verify the process is stopped using the below command.

$ systemctl status nginx

To change the default port (80) for HTTP, modify the below Nginx configuration file depending on the type of distribution you were using, using the text editor (nano, vim).

$ sudo nano /etc/nginx/sites-enabled/default [On Debian/Ubuntu] $ sudo nano /etc/nginx/nginx.conf [On CentOS/Fedora]

Below is the output of the above default and nginx.conf configuration files.

Nginx web configuration file in Debian Nginx web configuration file in RHELNginx web configuration file

Once the configuration file is opened, find the Listen 80 and Listen [::]: 80 string within the file and replace 80 with something else. For me, it’s 88 port, as shown below.

Nginx web configuration file with modifications in Debian Nginx web configuration file with modifications in RHELNginx web configuration file with the modification

After the configuration is saved with the modification for Debian or Ubuntu-based Distributions, start or restart the Nginx server using the below command.

$ sudo systemctl restart nginx [On Debian/Ubuntu]

During assigning port, RHEL-based distributions such as CentOS or Fedora require you to install policycoreutils and add the below rules required by SELinux for nginx.

$ sudo dnf install policycoreutils $ sudo semanage port -a -t http_port_t -p tcp 88 $ sudo semanage port -m -t http_port_t -p tcp 88

Finally, restart the Nginx web server to apply changes.

$ sudo systemctl restart nginx

Now Nginx is bound to the new port 88. You can check your local network socket table using the netstat command to find the Nginx port as listed below.

$ sudo netstat -tlpn| grep nginx

Below is the output of the above command.

Check the local network socket table using the netstat command

Finally, open your Web browser (Chrome, Firefox, etc.) and enter http://localhost:88 .

Innovative tech mind with 12 years of experience working as a computer programmer, web developer, and security researcher. Capable of working with a variety of technology and software solutions, and managing databases.

Источник

Оцените статью
Adblock
detector