Linux local http server

How do you set up a local testing server?

This article explains how to set up a simple local testing server on your machine, and the basics of how to use it.

Prerequisites: You need to first know how the Internet works, and what a Web server is.
Objective: You will learn how to set up a local testing server.

Local files vs. remote files

Throughout most of the learning area, we tell you to just open your examples directly in a browser — this can be done by double-clicking the HTML file, dragging and dropping it into the browser window, or choosing File > Open… and navigating to the HTML file. There are many ways to achieve this.

If the web address path starts with file:// followed by the path to the file on your local hard drive, a local file is being used. In contrast, if you view one of our examples hosted on GitHub (or an example on some other remote server), the web address will start with http:// or https:// , to show that the file has been received via HTTP.

The problem with testing local files

Some examples won’t run if you open them as local files. This can be due to a variety of reasons, the most likely being:

  • They feature asynchronous requests. Some browsers (including Chrome) will not run async requests (see Fetching data from the server) if you just run the example from a local file. This is because of security restrictions (for more on web security, read Website security).
  • They feature a server-side language. Server-side languages (such as PHP or Python) require a special server to interpret the code and deliver the results.
  • They include other files. Browsers commonly treat requests to load resources using the file:// schema as cross-origin requests. So if you load a local file that includes other local files, this may trigger a CORS error.

Running a simple local HTTP server

To get around the problem of async requests, we need to test such examples by running them through a local web server.

Using an extension in your code editor

If you only need HTML, CSS and JavaScript, and no server-side language, the easiest way may be to check for extensions in your code editor. As well as automating installation and set-up for your local HTTP server, they also integrate nicely with your code editors. Testing local files in an HTTP server may be one click away.

Читайте также:  Running linux shell on windows

For VSCode, you can check the following free extension:

Using Python

Another way to achieve this is to use Python’s http.server module.

Note: Older versions of Python (up to version 2.7) provided a similar module named SimpleHTTPServer . If you are using Python 2.x, you can follow this guide by replacing all uses of http.server with SimpleHTTPServer . However, we recommend you use the latest version of Python.

  1. Install Python. If you are using Linux or macOS, it should be available on your system already. If you are a Windows user, you can get an installer from the Python homepage and follow the instructions to install it:
    • Go to python.org
    • Under the Download section, click the link for Python «3.xxx».
    • At the bottom of the page, click the Windows Installer link to download the installer file.
    • When it has downloaded, run it.
    • On the first installer page, make sure you check the «Add Python 3.xxx to PATH» checkbox.
    • Click Install, then click Close when the installation has finished.
  2. Open your command prompt (Windows) / terminal (macOS/ Linux). To check if Python is installed, enter the following command:
-V # If the above fails, try: python3 -V # Or, if the "py" command is available, try: py -V 
# include the directory name to enter it, for example cd Desktop # use two dots to jump up one directory level if you need to cd .. 
# If Python version returned above is 3.X # On Windows, try "python -m http.server" or "py -3 -m http.server" python3 -m http.server # If Python version returned above is 2.X python -m SimpleHTTPServer 

Note: If you already have something running on port 8000, you can choose another port by running the server command followed by an alternative port number, e.g. python3 -m http.server 7800 (Python 3.x) or python -m SimpleHTTPServer 7800 (Python 2.x). You can then access your content at localhost:7800 .

Running server-side languages locally

Python’s http.server (or SimpleHTTPServer for Python 2) module is useful, but it is merely a static file server; it doesn’t know how to run code written in languages such as Python, PHP or JavaScript. To handle them, you’ll need something more — exactly what you’ll need depends on the server-side language you are trying to run. Here are a few examples:

  • To run Python server-side code, you’ll need to use a Python web framework. There are many popular Python web frameworks, such as Django (a guide is available), Flask, and Pyramid.
  • To run Node.js (JavaScript) server-side code, you’ll need to use raw node or a framework built on top of it. Express is a good choice — see Express Web Framework (Node.js/JavaScript).
  • To run PHP server-side code, launch PHP’s built-in development server:
cd path/to/your/php/code php -S localhost:8000 

Found a content problem with this page?

This page was last modified on Jul 3, 2023 by MDN contributors.

Источник

Локальный веб-сервер под Linux, с автоматическим поднятием хостов и переключением версий PHP

Скорее всего какие-то части этой статьи уже знакомы многим хаброжителям, но в связи с покупкой нового рабочего ноутбука я решил собрать все крупинки воедино и организовать удобное средство для разработки. Мне часто приходится работать со множеством маленьких проектов, с разными версиями PHP, часто переводить старые проекты на новые версии. В далёком прошлом, когда я был пользователем Windows то использовал OpenServer. Но с переходом на Linux мне нехватало той простоты создания хостов и переключений версий которые были в нём. Поэтому пришлось сделать еще более удобное решение на Linux =)

Цели

  1. Использовать текущий на момент написания статьи софт
  2. Чтоб разграничить локальные домены, будем использовать специальный домен .loc
  3. Переключения версий PHP реализуем через поддомен c помощью fast-cgi
  4. Автоматическое создание хоста с помощью vhost_alias и dnsmasq

будет запущен тот же файл но уже с версией PHP 7.2.7

Другие версии доставляются аналогичным описанным ниже способом.

Для создания еще одного сайта просто создаем в /var/www/ папку имеющую окончание .loc, внутри которой должна быть папка public_html являющаяся корнем сайта

Вот собственно и все. Как без дополнительных мучений, перезапусков, и редактирований конфигов имеем автоматическую систему для работы с сайтами.

Всё это я проверну на LinuxMint19, он на базе Ubuntu18.04, так что с ним все будет аналогично.

Для начала поставим необходимые пакеты

sudo apt update sudo apt install build-essential pkg-config libxml2-dev libfcgi-dev apache2 libapache2-mod-fcgid postfix 

Postfix ставим в качестве плюшки, как простое решение(в мастере установки, всё по умолчанию выбираем) для отправки почты с локальной машины.

Так как это локальная разработка и я единственный пользователь. То мне удобней перенести папку с проектами в мою домашнюю дерикторию. Она у меня маунтится отдельным диском и мигрирует при переустановке системы. Самый простой способ это создать ссылку, тогда не нужно менять пути в настройках да и путь привычный для всех.

Скопируем папку созданную апачем в домашний каталог, создадим на ее месте ссылку, не забыв поменять пользователя на себя и обменяться группами с апачем.

sudo mv /var/www/ ~/www sudo ln -s ~/www /var/www sudo chown $USER:$USER -R ~/www sudo usermod -a -G www-data $USER sudo usermod -a -G $USER www-data 

Создадим папку в которой будем собирать исходники PHP для разных версий

sudo mkdir /usr/local/src/php-build 

Также нам понадобится папки для CGI скриптов

И runtime папка для этих же скриптов, с правами

sudo mkdir /var/run/mod_fcgid sudo chmod 777 /var/run/mod_fcgid 

И так как каталог у нас находится в оперативной памяти, добавим его создание при старте системы, для этого добавим в /etc/tmpfiles.d/fcgid.conf

 #Type Path Mode UID GID Age Argument d /var/run/mod_fcgid 0755 www-data www-data - - 

У меня dnsmasq-base идет с коробки, если нет то его всегда можно доставить.

sudo updatedb locate dnsmasq.conf 

Либо если он как и у меня является частью NetworkManager то создать новый файл конфигурации в /etc/NetworkManager/dnsmasq.d/local.conf
Добавим в него строчку для перенаправление нашего локального домена на локальную машину.

Также нужно включить необходимые модули апача

sudo a2enmod fcgid vhost_alias actions rewrite 

Предварительная подготовка завершена, приступаем к сборке различных локальных версий PHP. Для каждой версии PHP проделываем следующие 4 шага. На примере 5.6.36

1. Скачиваем исходники нужной версии и распаковываем их

cd /usr/local/src/php-build sudo wget http://pl1.php.net/get/php-5.6.36.tar.bz2/from/this/mirror -O php-5.6.36.tar.bz2 sudo tar jxf php-5.6.36.tar.bz2 

2. Cобираем из исходников нужную версию PHP, и помещаем ее в /opt/php-5.6.36

sudo mkdir /opt/php-5.6.36 cd php-5.6.36 sudo ./configure --prefix=/opt/php-5.6.36 --with-config-file-path=/opt/php-5.6.36 --enable-cgi sudo make sudo make install sudo make clean 

3. Создаем CGI для обработки этой версии в /var/www/cgi-bin/php-5.6.36.fcgi

#!/bin/bash PHPRC=/opt/php-5.6.36/php.ini PHP_CGI=/opt/php-5.6.36/bin/php-cgi PHP_FCGI_CHILDREN=8 PHP_FCGI_MAX_REQUESTS=3000 export PHPRC export PHP_FCGI_CHILDREN export PHP_FCGI_MAX_REQUESTS exec /opt/php-5.6.36/bin/php-cgi 

4. Делаем файл исполняемым

sudo chmod +x /var/www/cgi-bin/php-5.6.36.fcgi 

5. Добавляем экшен для обработки каждой версии в /etc/apache2/mods-available/fcgid.conf

 AddHandler fcgid-script fcg fcgi fpl Action application/x-httpd-php-5.6.36 /cgi-bin/php-5.6.36.fcgi AddType application/x-httpd-php-5.6.36 .php #Action application/x-httpd-php-7.2.7 /cgi-bin/php-7.2.7.fcgi #AddType application/x-httpd-php-7.2.7 .php FcgidIPCDir /var/run/mod_fcgid FcgidProcessTableFile /var/run/mod_fcgid/fcgid_shm FcgidConnectTimeout 20 AddHandler fcgid-script .fcgi  

6. Добавляем правило для обработки каждой версии в /etc/apache2/sites-available/000-default.conf

 #Универсальный ServerNamе ServerAlias *.loc #Алиас для CGI скриптов ScriptAlias /cgi-bin /var/www/cgi-bin #Универсальный DocumentRoot VirtualDocumentRoot /var/www/%2+/public_html #Директория тоже должна быть универсальной Options +ExecCGI -Indexes AllowOverride All Order allow,deny Allow from all #Ниже все условия для каждой из версий =~ /56\..*?\.loc/"> SetHandler application/x-httpd-php-5.6.36 #По умолчанию, если версия не указанна, запускаем на последней SetHandler application/x-httpd-php-7.2.7   ErrorLog $/error.log CustomLog $/access.log combined 

Ну вот и всё. Осталось только перезапустить apache и dnsmasq и пользоваться

sudo service apache2 restart sudo service network-manager restart 

Источник

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