Estou executando um servidor web Apache em uma máquina desktop executando o Trisquel 8 (baseado no Ubuntu). Eu gostaria de tornar o servidor acessível a outras máquinas/dispositivos na minha rede local, mas não consigo descobrir como.
Quando tento me conectar de outro dispositivo, usando o endereço IP local do servidor Apache, recebo mensagens de erro no navegador, como: no Firefox em um Mac, recebo 'Não foi possível conectar. O Firefox não pode estabelecer uma conexão com o servidor em localhost.'. Se eu tentar conectar usando o navegador DuckDuckGo em um telefone Android, recebo 'Página da Web não disponível. A página da Web em http://localhost/ não pôde ser carregada porque: net::ERR_CONNECTION_REFUSED'.
Uma das respostas sugerida usar nmap
para ver quais portas estão abertas, que retornou o seguinte resultado:
$ nmap [LOCAL IP ADDRESS]
Starting Nmap 7.01 ( https://nmap.org ) at 2019-10-12 09:25 EDT
Nmap scan report for [LOCAL IP ADDRESS]
Host is up (0.00013s latency).
Not shown: 998 closed ports
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
Nmap done: 1 IP address (1 host up) scanned in 0.09 seconds
Então, mostra que a porta 80 está aberta para http. Provavelmente também vale a pena mencionar que posso pingar a máquina de outra na rede local e, como mostra a saída do nmap, tenho outra porta aberta para ssh. Eu tenho ssh-ing para esta máquina por vários meses e isso funciona muito bem. Para isso, acabei de instalar o ssh-server e funcionou praticamente fora da caixa.
Então, isso implica que algo está errado com a configuração do Apache2 (em oposição ao iptables/firewall), dado que o ssh está funcionando sem problemas?
Conteúdo do iptables:
$ sudo iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
ACCEPT tcp -- anywhere anywhere tcp dpt:http ctstate NEW,ESTABLISHED
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
Conteúdo do apache2.conf:
# This is the main Apache server configuration file. It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.4/ for detailed information about
# the directives and /usr/share/doc/apache2/README.Debian about Debian specific
# hints.
#
#
# Summary of how the Apache 2 configuration works in Debian:
# The Apache 2 web server configuration in Debian is quite different to
# upstream's suggested way to configure the web server. This is because Debian's
# default Apache2 installation attempts to make adding and removing modules,
# virtual hosts, and extra configuration directives as flexible as possible, in
# order to make automating the changes and administering the server as easy as
# possible.
# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
# /etc/apache2/
# |-- apache2.conf
# | `-- ports.conf
# |-- mods-enabled
# | |-- *.load
# | `-- *.conf
# |-- conf-enabled
# | `-- *.conf
# `-- sites-enabled
# `-- *.conf
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
# together by including all remaining configuration files when starting up the
# web server.
#
# * ports.conf is always included from the main configuration file. It is
# supposed to determine listening ports for incoming connections which can be
# customized anytime.
#
# * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/
# directories contain particular configuration snippets which manage modules,
# global configuration fragments, or virtual host configurations,
# respectively.
#
# They are activated by symlinking available configuration files from their
# respective *-available/ counterparts. These should be managed by using our
# helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See
# their respective man pages for detailed information.
#
# * The binary is called apache2. Due to the use of environment variables, in
# the default configuration, apache2 needs to be started/stopped with
# /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
# work with the default configuration.
# Global configuration
#
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE! If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the Mutex documentation (available
# at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"
#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
Mutex file:${APACHE_LOCK_DIR} default
#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}
#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300
#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On
#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100
#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5
# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log
#
# LogLevel: Control the severity of messages logged to the error_log.
# Available values: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the log level for particular modules, e.g.
# "LogLevel info ssl:warn"
#
LogLevel warn
# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf
# Include list of ports to listen on
Include ports.conf
# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
<Directory />
Options FollowSymLinks
AllowOverride None
Require all denied
</Directory>
<Directory /usr/share>
AllowOverride None
Require all granted
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
# Require local
# Require ip 192.168.1
Require all granted
</Directory>
#<Directory /srv/>
# Options Indexes FollowSymLinks
# AllowOverride None
# Require all granted
#</Directory>
# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives. See also the AllowOverride
# directive.
#
AccessFileName .htaccess
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<FilesMatch "^\.ht">
Require all denied
</FilesMatch>
#
# The following directives define some format nicknames for use with
# a CustomLog directive.
#
# These deviate from the Common Log Format definitions in that they use %O
# (the actual bytes sent including headers) instead of %b (the size of the
# requested file), because the latter makes it impossible to detect partial
# requests.
#
# Note that the use of %{X-Forwarded-For}i instead of %h is not recommended.
# Use mod_remoteip instead.
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.
# Include generic snippets of statements
IncludeOptional conf-enabled/*.conf
# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
Eu preciso do AllowOverride All
under /var/www
porque estou tentando executar uma instância do Wordpress e precisa ser capaz de gravar no servidor Apache.
O Apache2 está definitivamente em execução, pois posso acessar o conteúdo da web usando 'localhost' de um navegador na máquina local. Além disso, systemctl status apache2
mostra que está em execução:
~$ systemctl status apache2
● apache2.service - LSB: Apache2 web server
Loaded: loaded (/etc/init.d/apache2; bad; vendor preset: enabled)
Drop-In: /lib/systemd/system/apache2.service.d
└─apache2-systemd.conf
Active: active (running) since Thu 2019-10-10 20:01:44 EDT; 5min ago
Docs: man:systemd-sysv-generator(8)
Process: 1562 ExecStart=/etc/init.d/apache2 start (code=exited, status=0/SUCCESS)
CGroup: /system.slice/apache2.service
├─1621 /usr/sbin/apache2 -k start
├─1624 /usr/sbin/apache2 -k start
├─1625 /usr/sbin/apache2 -k start
├─1626 /usr/sbin/apache2 -k start
├─1627 /usr/sbin/apache2 -k start
├─1628 /usr/sbin/apache2 -k start
└─2102 /usr/sbin/apache2 -k start
Oct 10 20:01:42 lee-Desktop systemd[1]: Starting LSB: Apache2 web server...
Oct 10 20:01:42 lee-Desktop apache2[1562]: * Starting Apache httpd web server apache2
Oct 10 20:01:43 lee-Desktop apache2[1562]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
Oct 10 20:01:44 lee-Desktop apache2[1562]: *
Oct 10 20:01:44 lee-Desktop systemd[1]: Started LSB: Apache2 web server.
Conforme sugerido nos comentários, tentei netstat --inet -a | grep apache2
, mas não retornou nada. Aparentemente, isso é incomum se o apache2 estiver em execução, pois deve estar ouvindo na porta 80. Corri netstat -plunt | grep :80
e obtive a seguinte saída:
$ sudo netstat -plunt | grep :80
tcp6 0 0 :::80 :::* LISTEN 1557/apache2
Isso significa que o Apache está ouvindo, mas não está ouvindo nada?
Em termos das configurações do virtualhost, que também foram solicitadas, o único arquivo /etc/apache2/sites-enabled/
é 000-default.conf, cujo conteúdo é:
<VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
#ServerName www.example.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
</VirtualHost>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
Eu também tentei executar tail -f /var/log/apache2/*.log
, mas nada está sendo impresso nos logs quando tento conectar de uma máquina remota.
Então, como posso solucionar o que está bloqueando a conexão? Existe um log em algum lugar que possa me esclarecer por que a conexão está sendo recusada e por qual motivo?
Tentei as sugestões feitas por Jacob em sua resposta, mas infelizmente não resolveu o problema. Qualquer outra sugestão ou orientação seria muito apreciada!
ip addr
(orifconfig
) command run as root on the serverReasons below, also see Postscript for other far-fetching possibilities regarding your router and server configuration.
This smells really fishy, it says that local IP address you used for connecting is very, very, wrong.
If said local IP address in question is something closely resembling
127.0.0.1
or::1
, the address itself is likely to be the root cause of your problem. Because that is not a "real" IP address...IPv4 address
127.0.0.1
or abbreviated IPv6 address::1
means this device, and host namelocalhost
is always locally defined as synonym of this address.When you tried to connect to this address from any device other than the server itself, you are instructing it to connect to port 80 of itself (not the port 80 of server machine).
Since your other device did not run HTTP server on itself, the connection attempt will certainly end with TCP
RST
failure, i.e. the "Connection refused" error you got on your browser.For a remedy: you must use a correct LAN IP address when connecting from other machines: certainly not
localhost
, not127.0.0.1
, and not::1
...Run a command
ifconfig
as root on the server, and look for a block that is NOT namedlo
. The IP address will be a field calledinet addr:
.eth
followed by number, e.g.eth0
.wlan
followed by number, e.g.wlan0
.RUNNING
status (which shows that the LAN connection is enabled and usable).Try starting a browser on the server, then enter that IP address you found in step 1 in the address bar, press Enter.
Postscript
If the IP address you used is correct, then there might be other less-obvious reasons that could cause this problem, like:
You home router may be configured with "Virtual LAN" or port isolation— which would isolate each LAN port and each wireless LAN device in its own little network. Each device is confined and cannot connect to each other (and is only allowed to go straight to the Internet).
Your home router might incorporate layer 3 switch functionalities and is configured with access control list (i.e. firewall) to reject any "incoming connection" to any private LAN IP address, no matter of traffic's origin.
Thus, when your device tried to connect to your server, the router (or rather, the switch) intercepted, and replied back with TCP
RST
instead— resulting in "Connection refused" error.There might be something on your server that produces HTTP 301/302 redirect to
http://localhost/
. This could explain why your other device shownlocalhost
in the address bar even when you entered a real LAN IP address.Namely, the first request went all right; but due to some misconfiguration/misperception occurred on the server or server-side scripts, the client got redirected to
http://localhost/
, which is an incorrect address for reasons already lined in the main section of the answer...The end result is "Connection refused" error in the second request, and
http://localhost/
being in the address bar.Don't debug this with browser, since HTTP 301 redirect is cached. Use GNU
wget
or similar tools to issue request from other device, and look at its output carefully. If you see a redirection status came up before the "Connection refused" error— then that is not a network problem, but rather a server problem.If this happen to be the case, you will need find out what caused the server to produce the redirect, and fix it.
If you got this web root from somewhere else, it might contain a configuration which produces a redirection when it found that client accessed it using non-canonical host name. (This is very common, like when you go to www.stackexchange.com, it would produce a HTTP 301 redirect to stackexchange.com)
If your web application perceived its canonical host name to be just
localhost
, then it would inadvertently produce problematic redirection tohttp://localhost/
.In this case, specifically check your
.htaccess
and application's configuration; then disable said redirect.Primeiro, verifique se o httpd está sendo executado com
sudo systemctl httpd status
. Antes de adicionarmos acidentalmente uma regra duplicada, vamos verificar as regras do iptables comiptables -L
Para ter certeza de que aceitamos todos os http recebidos, vamos adicionar um ACCEPT à nossa tabela
se isso não resolver o problema, verifique as configurações do apache encontradas em
/etc/apache2/apache2.conf
. Devemos ter um modelo básico de segurança na parte inferior do arquivo conf. Por exemplo, isso é o que se encontra no meuIn ports.conf be sure that we are listening to port 80 on all devices (for now until we get you set up)
Listen *:80
If none of these are causing an issue, check that apache2 is running aswell
If you use localhost as a host name from other machines, they try to connect to themselves... On the other machines you have to use the actual address of your server. So
ip address show
this will list all your net interfaces and the addresses (inet
lines that look like:inet 192.168.0.44/24 brd 192.168.0.255 scope global dynamic enp0s31f6
). Ignore thelo
interface (which is the one at address 127.0.0.1), and use theenp*
orwlp*
ones. These will likely have address starting with192.168...
inet
line on your Mac/or Android: http://192.168.0.44/Using the address directly has two inconvenients:
On the Mac you can likely fix problem #2 by adding your server name and address in the
/etc/hosts
file (or whatever its equivalent on OSX). This may no be doable on Android.For #1, if you are extremely lucky all your devices support NETBIOS name resolution and you can use their NETBIOS names (usually their host name).
Posting my own answer, just to clarify what the problem was:
I used
curl --verbose [local-IP]
from the terminal of my Mac and it was clear from the output that it was getting to the Apache server, but Wordpress was redirecting tohttp://localhost/
. So, I checked the Wordpress settings and it hadhttp://localhost/
set as the 'site address'. I changed that tohttp://[local-IP]
and it now works fine. Thanks to everyone who made helpful suggestions!(I guess the moral of this story is to use command-line tools for debugging next time ...)
I have encountered the same problem once, i think you are setting up a local web server using virtual machine. If this is what you are doing please check the firewall configuration of your web server.
If you are able to access Apache server from the same machine and getting error while accessing the same from remote machine then kindly Allow apache in firewall in the web-server.
Run the below mentioned command (It worked on CentOS-7)
Let us know whether you are still facing the same issue.
You could use nmap from a remote computer to see if port 80 is being filtered.