Настройка прокси-сервера
Прокси-сервер фильтрует содержимое просматриваемых вами веб-сайтов. Он получает запросы на загрузку веб-страниц и их элементов от веб-браузера и, следуя заданным правилам, решает, пропускать их или нет. Обычно прокси используют в бизнесе и в публичных беспроводных точках доступа, чтобы управлять тем, какие сайты вы можете просматривать, запрещать пользователям доступ в Интернет без авторизации или проверять безопасность веб-сайтов.
Изменение режима прокси-сервера
Откройте Обзор и начните вводить: Сеть .
Нажмите Сеть чтобы открыть этот раздел настроек.
Выберите Прокси-сервер в списке слева.
Выберите нужный режим прокси-сервера из указанных:
Для получения web-содержимого, приложения будут использовать прямое подключение.
Для проксирования каждого протокола необходимо определить адрес прокси и порт для протоколов. Это протоколы: HTTP , HTTPS , FTP и SOCKS .
Адрес URL указывает на ресурс, содержащий подходящую для вашей системы конфигурацию.
Приложения, использующие сетевое соединение, будут использовать указанные параметры прокси.
How to Configure Proxy Settings on Ubuntu 20.04
Using a proxy server as an internet access intermediary is a common business scenario. However, personal users can also benefit from increased network security, privacy, and speed provided by proxies.
In this tutorial, you will learn how to set up your Ubuntu 20.04 system to work with a proxy server.

- Ubuntu 18.04 or later
- Access to terminal with sudo privileges
- Proxy info (web or IP address, username, and password)
Note: If you wish to set up one of your machines to act as a proxy, refer to How to Set Up & Install Squid Proxy Server on Ubuntu.
Setting Up Proxy with Ubuntu Desktop GUI
1. To access proxy settings using the Ubuntu GUI, open Ubuntu’s main Settings.
2. Select the Network setting in the menu on the left side of the window.
3. Then, click the cog in the Network Proxy section.

4. A Network Proxy dialogue appears. Choose Manual and enter your proxy info into the fields below.

5. Exit the dialogue and Ubuntu will automatically apply the proxy settings.
Setting up Proxy With Ubuntu Desktop Terminal
Use the command line interface for more granular control of proxy settings. This allows you to:
- Make temporary or permanent changes to the configuration.
- Set up proxy for a single user or for all users.
Setting Up Temporary Proxy for a Single User
A temporary proxy connection resets after a system reboot. To establish such a connection for the current user, use the export command.
The syntax for establishing a temporary proxy connection is:
Provide the proxy address (web or IP), followed by the port number. If the proxy server requires authentication, add your proxy username and password as the initial values.
This is what the set of commands should look like in terminal:

The purpose of the NO_PROXY line is to tell the system that local traffic should ignore the proxy.
Setting Up Permanent Proxy for a Single User
As stated above, proxy settings configured through a terminal window reset after you reboot your system. To make permanent changes for a single user, edit the .bashrc file.
1. Open the file with a text editor of your choice:
2. Now add the following lines at the bottom of the .bashrc file:

3. Save and exit the file.
4. Then, run the following command in to apply the new settings to the current session:
Setting Up Permanent Proxy for All Users
To permanently set up proxy access for all users, you have to edit the /etc/environment file.
1. First, open the file in a text editor:
2. Next, update the file with the same information you added to the .bashrc file in the previous scenario:

3. Save the file and exit. The changes will be applied the next time you log in.
Setting Up Proxy for APT
On some systems, the apt command-line utility needs a separate proxy configuration, because it does not use system environment variables.
1. To define proxy settings for apt, create or edit (if it already exists) a file named apt.conf in /etc/apt directory:
2. Add the following lines to the file:

3. Save the file and exit. The configuration will be applied after a reboot.
This tutorial provided instructions on how to set up proxy settings on Ubuntu 20.04. You should now know how to make temporary and permanent changes to your system’s proxy configuration, for a single user or for the entire system.
Setting up Proxy in Ubuntu
This post is for complete newbies to Ubuntu Linux. It explains how to setup proxy.
Proxy in Network Settings
Most people know about this, but for the sake of completeness,
- Open System Settings in Ubuntu.
- Under Hardware, click on Network
- On the left hand side plane, click on Network Proxy
- In the Method drop down list, choose Manual
- Fill up the http and https proxy. No need to set ftp and socks proxy.
- Click on Apply system wide.
Proxy in /etc/apt/apt.conf
Just like you have a Google Play Store for downloading Android apps, you have an apt-get package manager for installing applications in Ubuntu.
If you have used Chrome or Firefox, you must have noticed that they interactively ask for proxy username and password. Unlike them, apt-get does not. Instead, it fails, saying “407 Proxy Authentication Required”
Fortunately, apt-get uses proxy that you store in a file “/etc/apt/apt.conf”
Lets open this file and have a look. Open a terminal, and type
We see that gedit(a text editor) opens the file, and it has the following contents.
Now, we modify the file as follows,
Replace <user>,<pass>,<proxy> and <port> by your actual details. Save and close the text file. If you get any GTK-Warning on your terminal, ignore it.
Now, to check if apt-get is working, type “sudo apt-get update” in the terminal and press enter.
If you have done everything correctly, you shouldn’t get the “407 Proxy Authentication Required” error anymore.
Proxy in
Setting Proxy in bashrc itself would just take a minute . You would just have to follow some instructions and everything would work.
But we are not going to do that. Instead, we are going to understand what we are doing and why we are doing it. Because that’s the Linux way.
Environment Variables
Before explaining about .bashrc file, I need to explain what environment variables are.
In Linux, an environment variable is a system variable. Its just like a variable that you know from any other programming language — It has a name and a value. But instead of being part of a program, its part of your terminal.
So, why do we need environment variables?
Broadly, environment variables provide information to the various processes running on your system.
The Proxy Environment Variables
One such example is the proxy environment variables.
To view the proxy environment variables, open a terminal and type,
The proxy environment variables are used by various processes to connect to the internet. One such example is the wget.
Try doing,
It will say something like,
Proxy tunneling failed: Proxy Authentication Required
As you might have guessed, wget is also like apt-get, in the sense that it doesn’t ask you for proxy username and password. Instead, it fails with a 407.
Remember 407. If you ever see it, you know that its a proxy issue.
Thus, we have to modify the proxy environment variables to include username and password.
Try doing,
Again, replace <user>, <pass>, <proxy> and <port> with your own details. Example below.
Note : export is a Linux command used to set and modify environment variables.
Then, try the wget again. This time, it will work.
The screenshot is given for your reference.
All seems good. Close the terminal.
But wait, its not so simple.
Open another terminal and type,
You will see that the proxy environment variables have been reset.
Environment variables belong to a shell. Changes made to the environment of one shell does is not reflected in another shell.
Thus, we have to type the export command every time we open a terminal . How tedious.
Here comes our lord and saviour — bashrc.
The bashrc file is a file that is executed when you open a terminal. Thus, you can put code into it, and it will be executed, as if you wrote that code after you opened the terminal.
So, we can put the export commands inside the bashrc file, and finally setup the proxy.
Open a terminal, and type,
And add the following lines at the top,
Of course, replace the details with your own.
Save and close the file.
Like I said earlier, bashrc runs every time you open a new shell. So close the terminal and open it again. Alternatively, you can run source to execute the bashrc file.
Now, lets try this once again.
Done. But is it?
If you reached here, then I have to say, you have successfully setup proxy in Linux.
But, the more you learn, the more there is to learn.
For example, bashrc method only works for a particular user. So if you run a command using sudo, it does not work.
To make it work, you have to use the -E option of sudo. Check out the man page of sudo to learn more about the -E option.
Also, what is the difference between shell and terminal? Are they the same?
Как настроить прокси в Ubuntu
С помощью прокси сервера вы можете скрыть свой реальный ip адрес и заставить веб-сайт думать, что вы совсем из другой страны или используете другого провайдера, чем это есть на самом деле. Прокси может использоваться не только для просмотра сайтов интернета, но и для обновления системы, загрузки пакетов через apt и многого другого.
В этой статье мы поговорим о том как выполняется настройка прокси Ubuntu с помощью графического интерфейса или через терминал.
Настройка прокси на Ubuntu через GUI
В Ubuntu можно настроить прокси Ubuntu через стандартное приложение Параметры. Откройте программу, затем перейдите в раздел Сеть и кликните по шестеренке Сетевой прокси:

Здесь надо прописать IP адрес вашего прокси и порт в подходящем поле. Это зависит от типа вашего прокси, например, HTTP/HTTPS или SOCKS:

Если для прокси необходима авторизация, вы можете прописать данные авторизации в поле IP адреса:
логин : пароль @ ip_адрес
Теперь вы можете проверить работает ли новый прокси по всей системе. Например, через терминал:


Настройка прокси в Ubuntu через терминал
Все настройки среды рабочего стола в Ubuntu хранятся в базе данных DConf, в том числе и настройки прокси сервера. Настройки записываются в виде пар ключ значение. Если изменить какой либо параметр из меню настроек системы все изменения сразу же запишутся в DConf. Из командной строки настройками DConf можно управлять с помощью команд gsettings и dconf. Дальше я покажу как настроить прокси в Ubuntu из терминала с помощью gsettings.
Базовое использование gsettings для работы с базой данных Dconf выглядит следующим образом. Для чтения данных используем:
$ gsettings get <schema> <key>
А для редактирования:
$ gsettings set <schema> <key> <value>
Рассмотрим подробнее как выполняется настройка прокси через консоль Ubuntu. Выполните следующие команды чтобы установить в качестве прокси сервера my.proxy.com:8000
gsettings set org.gnome.system.proxy.http host ‘my.proxy.com’ gsettings set org.gnome.system.proxy.http port 8000 gsettings set org.gnome.system.proxy mode ‘manual’

Если вы хотите использовать HTTPS/FTP прокси то вам нужно выполнить:
gsettings set org.gnome.system.proxy.https host ‘my.proxy.com’ gsettings set org.gnome.system.proxy.https port 8000 gsettings set org.gnome.system.proxy.ftp host ‘my.proxy.com’ gsettings set org.gnome.system.proxy.ftp port 8000
Для использования SOCKS прокси наберите:
gsettings set org.gnome.system.proxy.socks host ‘my.proxy.com’ gsettings set org.gnome.system.proxy.socks port 8000
Все изменения действуют только для текущего пользователя. Если вы хотите установить прокси для всех пользователей запускайте gsettings от суперпользователя добавив перед командой sudo, например:
sudo gsettings set org.gnome.system.proxy.http host ‘my.proxy.com’ sudo gsettings set org.gnome.system.proxy.http port 8000 sudo gsettings set org.gnome.system.proxy mode ‘manual’
Если вы используете автоматическую настройку прокси можете выполнить следующие команды:
gsettings set org.gnome.system.proxy mode ‘auto’ gsettings set org.gnome.system.proxy autoconfig-url http://my.proxy.com/autoproxy.pac
Для того чтобы удалить прежние настройки прокси и работать напрямую выполните:
gsettings set org.gnome.system.proxy mode ‘none’
Чтобы прописать прокси в Ubuntu с авторизацией, записывайте в поле host логин и пароль в том же формате, который предложен для настройки в графическом интерфейсе.
Утилита apt тоже умеет работать с глобальным прокси, настроенным как описано выше, однако вы можете настроить для неё прокси отдельно через конфигурационный файл /etc/apt/apt.conf. Для этого добавьте в этот одну из строк для активации нужного типа прокси:
sudo vi /etc/apt/apt.conf
Acquire::http::proxy «логин:пароль@ip_адрес:порт/»; Acquire::https::proxy «логин:пароль@ip_адрес:порт/»;
И непосредственно для активации прокси:
Acquire. Proxy «true»;
После этого пакетный менеджер apt будет использовать свой отдельный прокси для обновления Ubuntu.
Выводы
В этой небольшой статье мы поговорили о том, как выполняется настройка прокси Ubuntu. Как видите, это совсем не сложно. Если вы хотите зайти с другой стороны и вам нужно настроить прокси сервер, смотрите статью о том как установить squid в Ubuntu.
Похожие записи
Оцените статью
alt=»Creative Commons License» width=»» />
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
Об авторе
Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.
1 комментарий к “Как настроить прокси в Ubuntu”
Добрый день. А подскажите, если я в системных настройках указал так как вышеописанно прокси, а потом в броузере указал другое прокси, как будет идти траффик? через оба сразу показывая айпи последнего прокси или через броузерный, если указан, иначе через системный? просто не могу сообразить — если будет два — и один из них сломается, тогда связи не будет вообще?