Trying to use «rotatelogs» on Apache 2.2 as non-root

Содержание
  1. Don’t make these changes unless you’re absolutely certain you know what you’re doing!
  2. Can Apache run as non-root?
  3. How do I install Apache as non-root user?
  4. How do I run apache as root user?
  5. How can I tell what user apache is running as?
  6. Does AWS use Apache?
  7. Why does apache run as root?
  8. How to use non root privileges in Apache?
  9. Is it possible to run Apache as any user?
  10. How do I configure Apache to run from a non privileged operating system?
  11. How do I serve port 80?
  12. How do I run node on port 80?
  13. Can port 80 be closed?
  14. How do you protect ports?
  15. What is the most secure port?
  16. Which user does apache2 run as?
  17. Should Apache be installed as root?
  18. What user does xampp run as?
  19. How do I start apache2 as root?
  20. How is Apache configured to run as unprivileged user?
  21. How to find out what user Apache is running as?
  22. Can I run a server on port 80?
  23. How can I open port 80 so a non-root process?
  24. How to change Apache not binding to port 80?
  25. How Apache Starts
  26. Errors During Start-up
  27. Starting at Boot-Time
  28. Comments
  29. How Apache Starts ¶
  30. Errors During Start-up ¶
  31. Starting at Boot-Time ¶
  32. Comments
  33. ChrootDir Directive
  34. Group Directive
  35. Security
  36. See also
  37. Suexec Directive
  38. User Directive
  39. Security
  40. See also
  41. Comments
  42. Ответа
  43. Другие вопросы по тегам:
  44. Похожие вопросы:
  45. Managing many virtual hosts
  46. Using apache2-mpm-worker and mod_fcgid
  47. Using php-fpm and mod_proxy_fcgi
  48. Test whether PHP works
  49. Apache Status and Logs
  50. Error: PID file /run/httpd/httpd.pid not readable (yet?) after start
  51. /run/httpd not being created at boot
  52. Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe.
  53. AH00534: httpd: Configuration error: No MPM loaded.
  54. AH00072: make_sock: could not bind to address
  55. AH01071: Got error ‘Primary script unknown’
  56. Changing the max_execution_time in php.ini has no effect
  57. PHP-FPM: errors are not being logged separately per virtual host

Don’t make these changes unless you’re absolutely certain you know what you’re doing!

The httpd.conf file for the default Apache2 installation that comes with OS X can be found in /private/etc/apache2/httpd.conf. Before you make any changes to this file BACK IT UP! That way you can get back to a sane starting place if you make a catastrophically bad change.

# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch...
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User _www
Group _www
User root
Group wheel

Once you’ve made the changes, restart Apache with:

sudo /usr/sbin/apachectl restart

and you should be running as root.

Again: BE CAREFUL DOING THIS!

Can Apache run as non-root?

How do I install Apache as non-root user?

  1. Download source.
  2. Decompress it.
  3. cd to httpd source directory.
  4. ./configure –prefix=/home/youruser/httpd -otheroptionshere.
  5. make install.

How do I Harden Apache?

In this article, you can find 10 security tips to harden your Apache configuration and improve Apache security in general.

  1. Disable the server-info Directive.
  2. Disable the server-status Directive.
  3. Disable the ServerSignature Directive.
  4. Set the ServerTokens Directive to Prod.
  5. Disable Directory Listing.

How do I run apache as root user?

  1. Create a shell script that does what you want.
  2. In a terminal window, execute the command sudo vi /etc/sudoers and insert the following line at the end of the file (important to be at end so the other commands do not override): ALL ALL=NOPASSWD: /localstore/root.sh.

How can I tell what user apache is running as?

  1. Open Apache’s configuration file using your preferred text editor.
  2. Find User and Group directives in Apache’s configuration file.
  3. Set the value to existing user and group that you want Apache process to run as.

Does AWS use Apache?

Apache on the other hand is a SOFTWARE that run on servers. So, essentially you can run Apache on AWS. That is the basic idea. AWS is a platform and Apache can run on top of AWS.

Why does apache run as root?

How to use non root privileges in Apache?

Is it possible to run Apache as any user?

Do you need to configure Apache to start automatically?

Apache will now start automatically when the server boots again. The default configuration for Apache will allow your server to host a single website. If you plan on hosting multiple domains on your server, you will need to configure virtual hosts on your Apache web server.

https://youtube.com/watch?v=CXX_DeFV-ik%3Ffeature%3Doembed%26wmode%3Dopaque


Method 1: Sudo privileges

  1. Provide the non-root account sudo privileges to start the service. For example test user wants to start Apache service.
  2. Add the following configuration to /etc/sudoers file. In case your user is different, replace the test user with the user account name of your choice.

Does Apache need to run as root?

How do I configure Apache to run from a non privileged operating system?

Run Apache from a non-privileged account

  1. Go to $Web_Server/conf.
  2. Modify httpd.conf using vi.
  3. Search for User & Group Directive and change as non-privileged account apache.

How can I use port 80 without rooting?

How do I serve port 80?

  1. >= Angular 6: edit the angular.json file and in the serve object (under object), add this piece of code: “options”: { “port”: 80 }
  2. Angular < 6.0: edit the angular-cli.json file and in the defaults object, add this piece of code: “serve”: { “port”: 80 }

Which command is used to access port 80 directly?

HTTP Protocol Basics Execute telnet SERVERNAME 80 . Thereby, telnet will connect to the server named SERVERNAME through port 80. If the establishment of the TCP connection is possible, telnet will respond with the messages: Connected to SERVERNAME.

How do I run node on port 80?

The simplest solution: safely configure your node app to run on port 80.

  1. sudo apt-get install libcap2-bin.
  2. sudo setcap cap_net_bind_service=+ep /path/to/node.

Do I need to open port 80?

If you have a webserver running, them you need to secure it as you would any public facing server. There is no inherent risk in leaving 80/tcp open to the internet that you don’t have with any other port.

Can port 80 be closed?

Allowing port 80 doesn’t introduce a larger attack surface on your server, because requests on port 80 are generally served by the same software that runs on port 443. Closing port 80 doesn’t reduce the risk to a person who accidentally visits your website via HTTP.

Can port 80 be used for https?

By default, HTTPS connections use TCP port 443. HTTP, the unsecure protocol, uses port 80.

How do you protect ports?

Monitor and filter DNS to avoid exfiltration. And stop using Telnet and close port 23. Security across all network ports should include defense-in-depth. Close any ports you don’t use, use host-based firewalls on every host, run a network-based next-generation firewall, and monitor and filter port traffic, says Norby.

What are the most vulnerable ports?

What is the most secure port?

Port 22 is SSH (Secure Shell), port 80 is the standard port for HTTP (Hypertext Transfer Protocol) web traffic, and port 443 is HTTPS (Hypertext Transfer Protocol Secure)—the more secure web traffic protocol.

What are good ports to use?

1024-5000 have been used by a number of OSes. IANA officially recommends 49152-65535 for the Ephemeral Ports. Port 8080 is the most common “high” port that people use (i.e. alternate web server port). Avoiding that is a good idea.

  1. Download source.
  2. Decompress it.
  3. cd to httpd source directory.
  4. ./configure –prefix=/home/youruser/httpd -otheroptionshere.
  5. make install.
  1. export APACHE_RUN_USER=www-data. export APACHE_RUN_GROUP=www-data.
  2. export APACHE_RUN_USER=nim. export APACHE_RUN_GROUP=nim.
  3. sudo chown -R nim /var/www/html/* sudo chgrp -R nim /var/www/html/*
  4. sudo chown -R nim /n/media. sudo chgrp -R nim /n/media.

Which user does apache2 run as?

Does apache2 run as root?

5 Answers. Apache has to run as root initially in order to bind to port 80. If you don’t run it as root initially then you cannot bind to port 80.

Should Apache be installed as root?

  1. sudo nano /etc/apache2/envvars.
  2. export APACHE_RUN_USER=user export APACHE_RUN_GROUP=user.
  3. sudo service apache2 restart.

What user does xampp run as?

How do I run apache2 as root?

  1. Create a shell script that does what you want.
  2. In a terminal window, execute the command sudo vi /etc/sudoers and insert the following line at the end of the file (important to be at end so the other commands do not override): ALL ALL=NOPASSWD: /localstore/root.sh.

How do I start apache2 as root?

Does Httpd run as root?

How is Apache configured to run as unprivileged user?

Is there a way to run Apache server without using sudo?

How to find out what user Apache is running as?

Can I run a server on port 80?

You can use any port you like but traditionally port 80 is used for “regular” http traffic and 443 for secure traffic, 21 for FTP, etc. You can host multiple websites on a single server, all using port 80 for as long as the server supports HTTP 1.1 protocol – pretty much all modern servers do.

How do I stop Apache from running on port 80?

Stop Apache2 from restarting on port 80 on boot

  1. sudo update-rc. d apache2 disable.
  2. sudo update-rc. d -f apache2 remove.
  3. sudo apt remove apache2. *

How can I open port 80 so a non-root process?

How to change Apache not binding to port 80?

PORT STATE SERVICE 22/tcp open ssh 25/tcp open smtp 80/tcp open http <~ make sure service is http 443/tcp open https If something other than http is using port 80, you can either change the apache config and point it to a different port or change the service that is using port 80 to a different port. Here’s a guide to install nmap

Дополнительно:  Как исправить ошибку Windows 10 0x8007007b - Инструменты для ошибок

How to run Apache on a privileged port?

I ma trying to make a Docker container image with an Apache server that handles TLS mutual authentication. Since this is a container Apache can be made to listen some high-numbered port instead of 443, so this should remove the need for root execution.

However, as soon as I try to enable TLS, I get this:

[Thu Oct 11 09:50:50.357758 2018] [auth_digest:notice] [pid 22] AH01757: generating secret for digest authentication ...
[Thu Oct 11 09:50:50.357818 2018] [auth_digest:error] [pid 22] (13)Permission denied: AH01762: Failed to create shared memory segment on file /run/httpd/authdigest_shm.22
[Thu Oct 11 09:50:50.357825 2018] [auth_digest:error] [pid 22] (13)Permission denied: AH01760: failed to initialize shm - all nonce-count checking, one-time nonces, and MD5-sess algorithm disabled

Gerald Schneider's user avatar

asked Oct 11, 2018 at 10:05

xenoid's user avatar

Applications in containers usually run as root. But that doesn’t mean that they have full root privileges.

From the docker security documentation:

Just let it run as root inside the container.

answered Oct 11, 2018 at 10:10

Gerald Schneider's user avatar

Gerald Schneider

8 gold badges55 silver badges87 bronze badges

Eventually figured it out. Listing the access flags on /run/httpd shows:

drwx--x--- 3 root apache 4096 Sep 24 15:57 /run/httpd/

So only root can write there. So in the Dockerfile I added:

RUN chmod 770 /run/httpd

And it worked. Not sure it the best solution, though, and I welcome any comments that point out problems with that solution.

answered Oct 15, 2018 at 10:32

xenoid's user avatar

1 gold badge3 silver badges10 bronze badges

I got another solution for this. In your configuration you can define a directory that you can write, other than /run/httpd/. Like this:

DefaultRuntimeDir runtime/

This could be a directory relative to your ServerRoot

You can find the document about httpd core and mod_slotmem_shm

answered May 3, 2021 at 19:12

felixc's user avatar

Can this be done? I don’t see a method here:

asked Dec 4, 2015 at 22:48

jouell's user avatar

There is no need to do anything in respect of file ownership. Red Hat ships their systems with sensible defaults. Millions of web servers run every day with their httpd logs owned by root. Best practice is to leave well alone in this instance.

If you are using piped logs as your link suggests, then you will need to configure your own cron job to run as root.

This is all normal stuff.

answered Dec 5, 2015 at 11:18

user9517's user avatar

20 gold badges214 silver badges296 bronze badges

answered Nov 9, 2017 at 15:21

Chris Adams's user avatar

Chris Adams

2 silver badges7 bronze badges

When I run the ps -efH command to list out all the process, I can see Apache running as root and seems to have sub-processes running as www-data. Here’s the excerpt:

root     30117     1  0 09:10 ?        00:00:00   /usr/sbin/apache2 -k start
www-data 30119 30117  0 09:10 ?        00:00:00     /usr/sbin/apache2 -k start
www-data 30120 30117  0 09:10 ?        00:00:00     /usr/sbin/apache2 -k start
www-data 30121 30117  0 09:10 ?        00:00:00     /usr/sbin/apache2 -k start

user 99572 is fine's user avatar

asked Jul 29, 2011 at 15:37

Mridang Agarwalla's user avatar

Apache has to run as root initially in order to bind to port 80. If you don’t run it as root initially then you cannot bind to port 80. If you want to bind to some port above 1024 then yes, you can. Otherwise don’t worry about root. That is the parent Apache process and does not serve any requests. It will spawn child processes and drop privileges for handling requests.

answered Jul 29, 2011 at 16:01

bahamat's user avatar

The location of the master configuration file depends on compile-time options and varies per distribution, but /etc/apache2/apache2.conf is a good starting guess.

answered Jul 31, 2011 at 14:59

Shadur's user avatar

2 gold badges14 silver badges18 bronze badges

In Ubuntu at least, the settings for this are in /etc/apache2/envvars. Tweak those, then restart apache and you’re off and running.

answered Sep 30, 2014 at 19:49

mlissner's user avatar

2 gold badges15 silver badges19 bronze badges

Also, check out Apache2 ITK MPM.

It forks an Apache thread with the assigned uid/gid, this let’s you keep using mod_php. No more chmod/chown etc.

Jawa's user avatar

13 gold badges31 silver badges36 bronze badges

answered Aug 23, 2013 at 8:21

Olli's user avatar

What worked for me is going into apache config file:

/etc/apache2/httpd.conf

and bumped into:

User _www
Group _www

answered Oct 19, 2016 at 19:40

Mercury's user avatar

On Windows, Apache is normally run as a service.
For details, see Running Apache as a Service.

On Unix, the httpd program
is run as a daemon that executes continuously in the
background to handle requests. This document describes how
to invoke httpd.

top

How Apache Starts

The recommended method of invoking the httpd
executable is to use the apachectl control script. This
script sets certain environment variables that are necessary for
httpd to function correctly under some operating
systems, and then invokes the httpd binary.
apachectl will pass through any command line
arguments, so any httpd options may also be used with
apachectl. You may also directly edit the
apachectl script by changing the HTTPD
variable near the top to specify the correct location of the
httpd binary and any command-line arguments that you
wish to be always present.

The first thing that httpd does when it is
invoked is to locate and read the configuration file
httpd.conf. The location of this file is set at
compile-time, but it is possible to specify its location at run
time using the -f command-line option as in

/usr/local/apache2/bin/apachectl -f
/usr/local/apache2/conf/httpd.conf

If all goes well during startup, the server will detach from
the terminal and the command prompt will return almost
immediately. This indicates that the server is up and running.
You can then use your browser to connect to the server and view
the test page in the DocumentRoot directory.

top

Errors During Start-up

  • Trying to start the server on a privileged port when not
    logged in as the root user; or
  • Trying to start the server when there is another instance
    of Apache or some other web server already bound to the same
    Port.

For further trouble-shooting instructions, consult the
Apache FAQ.

top

Starting at Boot-Time

If you want your server to continue running after a system
reboot, you should add a call to apachectl to your
system startup files (typically rc.local or a file in
an rc.N directory). This will start Apache as
root. Before doing this ensure that your server is properly
configured for security and access restrictions.

The apachectl script is designed to act like a
standard SysV init script; it can take the arguments
start, restart, and stop
and translate them into the appropriate signals to
httpd. So you can often simply link
apachectl into the appropriate init directory. But be
sure to check the exact requirements of your system.

top

Comments

Notice:
This is not a Q&A section. Comments placed here should be pointed towards suggestions on improving the documentation or server, and may be removed by our moderators if they are either implemented or considered invalid/off-topic. Questions on how to manage the Apache HTTP Server should be directed at either our IRC channel, #httpd, on Libera.chat, or sent to our mailing lists.

On Windows, Apache is normally run as a service.
For details, see Running Apache as a Service.

On Unix, the httpd program
is run as a daemon that executes continuously in the
background to handle requests. This document describes how
to invoke httpd.

top

How Apache Starts ¶

The recommended method of invoking the httpd
executable is to use the apachectl control script. This
script sets certain environment variables that are necessary for
httpd to function correctly under some operating
systems, and then invokes the httpd binary.
apachectl will pass through any command line
arguments, so any httpd options may also be used with
apachectl. You may also directly edit the
apachectl script by changing the HTTPD
variable near the top to specify the correct location of the
httpd binary and any command-line arguments that you
wish to be always present.

The first thing that httpd does when it is
invoked is to locate and read the configuration file
httpd.conf. The location of this file is set at
compile-time, but it is possible to specify its location at run
time using the -f command-line option as in

/usr/local/apache2/bin/apachectl -f
/usr/local/apache2/conf/httpd.conf

If all goes well during startup, the server will detach from
the terminal and the command prompt will return almost
immediately. This indicates that the server is up and running.
You can then use your browser to connect to the server and view
the test page in the DocumentRoot directory.

top

Errors During Start-up ¶

  • Trying to start the server on a privileged port when not
    logged in as the root user; or
  • Trying to start the server when there is another instance
    of Apache or some other web server already bound to the same
    Port.

For further trouble-shooting instructions, consult the
Apache FAQ.

top

Starting at Boot-Time ¶

If you want your server to continue running after a system
reboot, you should add a call to apachectl to your
system startup files (typically rc.local or a file in
an rc.N directory). This will start Apache as
root. Before doing this ensure that your server is properly
configured for security and access restrictions.

Дополнительно:  How to fix the Windows Error 0x80004001 Error 0x80004001

The apachectl script is designed to act like a
standard SysV init script; it can take the arguments
start, restart, and stop
and translate them into the appropriate signals to
httpd. So you can often simply link
apachectl into the appropriate init directory. But be
sure to check the exact requirements of your system.

top

Comments

Notice:
This is not a Q&A section. Comments placed here should be pointed towards suggestions on improving the documentation or server, and may be removed by our moderators if they are either implemented or considered invalid/off-topic. Questions on how to manage the Apache HTTP Server should be directed at either our IRC channel, #httpd, on Libera.chat, or sent to our mailing lists.

top

ChrootDir Directive

This directive tells the server to chroot(8) to the
specified directory after startup, but before accepting requests
over the ‘net.

Note that running the server under chroot is not simple,
and requires additional setup, particularly if you are running
scripts such as CGI or PHP. Please make sure you are properly
familiar with the operation of chroot before attempting to use
this feature.

top

Group Directive

A group name
Refers to the given group by name.
# followed by a group number.
Refers to a group by its number.

Security

See also

top

Suexec Directive

When On, startup will fail if the suexec binary doesn’t exist
or has an invalid owner or file mode.

When Off, suEXEC will be disabled even if the suexec binary exists
and has a valid owner and file mode.

top

User Directive

A username
Refers to the given user by name.
# followed by a user number.
Refers to a user by its number.

Security

See also

Comments

Notice:
This is not a Q&A section. Comments placed here should be pointed towards suggestions on improving the documentation or server, and may be removed by our moderators if they are either implemented or considered invalid/off-topic. Questions on how to manage the Apache HTTP Server should be directed at either our IRC channel, #httpd, on Libera.chat, or sent to our mailing lists.

< ?php echo `whoami`;  ?>

задан
26 March 2012 в 18:26

Ответа

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

  1. Создайте сценарий оболочки, который делает то, что Вы хотите. Это не Сценарий PHP, когда PHP выполняется в веб-сервере, Вам нужен скрипт, который запущен Ubuntu. Вот образец:

    #!/bin/sh
    # script that runs as root
    whoami
    

    Я назвал этот файл /localstore/root.sh и необходимо поместить его куда-нибудь, который имеет смысл в системах (например. /home/www_data/bin).

  2. В окне терминала выполните команду sudo vi /etc/sudoers и вставьте следующую строку в конце файла (важный, чтобы быть в конце, таким образом, другие команды не переопределяют):

    ALL ALL=NOPASSWD: /localstore/root.sh
    

    Это позволит любому запускать скрипт как корень, после того как Вы тестируете и подтверждаете, что он работает, я настоятельно рекомендую (снова в целях безопасности), что Вы изменяете строку на

    nobody ALL=NOPASSWD: /localstore/root.sh
    

    но как наблюдаемое Бодхи, Apache должен работать как www-data в этом случае необходимо измениться nobody кому: www-data.Примечание: Я никогда не пробовал sudo с nobody как пользователь и не уверено, что это будет работать.

  3. В Вашем сценарии веб-сервера выполните сценарий оболочки в PHP следующим образом:

    < ?php
    exec ("sudo /localstore/root.sh");
    ?>
    

    Можно добавить параметры к сценарию в кавычках.

    Это должно получить его так root.sh сценарий выполняется как корень при вызове от веб-сервера. Если у Вас есть другие сценарии, они могут быть списком разделенных запятой значений на той же самой записи в sudoers файл. Удостоверьтесь, что полномочия на сценарии позволяют выполнение веб-сервером.

Интересно, не является ли это требованием из-за запуска в виртуальной среде с Виртуальным веб-сервером с использованием общего каталога, и в этом случае владение каталогом будет корневым, чтобы к нему могли обращаться как файловая система хоста, так и гостевая система. Решением может быть добавление группы www-data в группу vboxfs или что-то еще в вашей среде. Более подробно это обсуждается в . Эта статья

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

Require all granted

в моей конфигурации каталога, как описано в этой статье

Другие вопросы по тегам:

Похожие вопросы:

Apache is not required and thus not configured to have any other access for security reasons, as even an exploit to a poorly written PHP or Perl script will not escalate and cause much harm to the system.

Trying to use "rotatelogs" on Apache 2.2 as non-root

  1. Open Apache‘s configuration file using your preferred text editor.

    $ sudo vi /etc/apache2/apache2.conf
    Password:
  2.  root
     root
  3. $ sudo chown --recursive username:groupname /home/user/website/
  4. Restart Apache service for changes to take effect.

    $ sudo systemctl restart apache2 #Ubuntu, Debian, openSUSE and SLES
    $ sudo systemctl restart httpd # CentOS and Red Hat
  5. Check if the changes was successful.

    $ ps aux | grep apache2
    root      1188  0.0  0.1 162184  6664 ?        Ss   Mar29   0:02 /usr/sbin/apache2 -k start
    root  1197  0.0  0.1 162184  5668 ?        S    Mar29   0:00 /usr/sbin/apache2 -k start
    root  1198  0.0  0.1 162184  5916 ?        S    Mar29   0:00 /usr/sbin/apache2 -k start
    root  1200  0.0  0.1 162184  5684 ?        S    Mar29   0:00 /usr/sbin/apache2 -k start
    root  1201  0.0  0.1 162184  5684 ?        S    Mar29   0:00 /usr/sbin/apache2 -k start
    root  1202  0.0  0.1 162184  5684 ?        S    Mar29   0:00 /usr/sbin/apache2 -k start

Trying to use "rotatelogs" on Apache 2.2 as non-root

Discuss the article:

Comment anonymously. Login not required.

The Apache HTTP Server, or Apache for short, is a very popular web server, developed by the Apache Software Foundation.

This article describes how to set up Apache and how to optionally integrate it with PHP.

Install the package.

Apache configuration files are located in /etc/httpd/conf. The main configuration file is /etc/httpd/conf/httpd.conf, which includes various other configuration files. The default configuration file should be fine for a simple setup. By default, it will serve the directory /srv/http to anyone who visits your website.

To run Apache, start httpd.service. If everything is working correctly, visiting http://localhost/ should display a simple index page.

See the full list of Apache configuration directives and the directive quick reference.

These options in /etc/httpd/conf/httpd.conf might be interesting for you:

User http
For security reasons, as soon as Apache is started by the root user (directly or via startup scripts) it switches to this UID. The default user is http, which is created automatically during installation.
Listen 80
This is the port Apache will listen to. For Internet-access with router, you have to forward the port.
If you want to setup Apache for local development you may want it to be only accessible from your computer. Then change this line to Listen 127.0.0.1:80.
ServerAdmin you@example.com
This is the admin’s email address which can be found on e.g. error pages.
DocumentRoot "/srv/http"
This is the directory where you should put your web pages.
Change it, if you want to, but do not forget to also change <Directory "/srv/http"> to whatever you changed your DocumentRoot to, or you will likely get a 403 Error (lack of privileges) when you try to access the new document root. Do not forget to change the Require all denied line to Require all granted, otherwise you will get a 403 Error. Remember that the DocumentRoot directory and its parent folders must allow execution permission to others (can be set with chmod o+x /path/to/DocumentRoot), otherwise you will get a 403 Error.
AllowOverride None
This directive in <Directory> sections causes Apache to completely ignore .htaccess files. Note that this is now the default for Apache 2.4, so you need to explicitly allow overrides if you plan to use .htaccess files. If you intend to use mod_rewrite or other settings in .htaccess files, you can allow which directives declared in that file can override server configuration. For more info refer to the Apache documentation.

Tip: If you have issues with your configuration you can have Apache check the configuration with: apachectl configtest

More settings can be found in /etc/httpd/conf/extra/httpd-default.conf:

To turn off your server’s signature:

ServerSignature Off

To hide server information like Apache and PHP versions:

ServerTokens Prod

Include conf/extra/httpd-userdir.conf

Tango-inaccurate.pngThe factual accuracy of this article or section is disputed.Tango-inaccurate.png

You must make sure that your home directory permissions are set properly so that Apache can get there. Your home directory and ~/public_html must be executable for others («rest of the world»):

$ chmod o+x ~
$ chmod o+x ~/public_html
$ chmod -R o+r ~/public_html

Restart httpd.service to apply any changes. See also Umask#Set the mask value.

Firstly obtain a certificate. If you own a public domain, you can use Transport Layer Security#ACME clients.

LoadModule ssl_module modules/mod_ssl.so
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
Include conf/extra/httpd-ssl.conf
LoadModule rewrite_module modules/mod_rewrite.so

After obtaining a key and certificate, make sure the SSLCertificateFile and SSLCertificateKeyFile lines in /etc/httpd/conf/extra/httpd-ssl.conf point to the key and certificate. If a concatenated chain of CA certificates was also generated, add that filename against SSLCertificateChainFile.

Finally, restart httpd.service to apply any changes.

Note: You will need to add a separate <VirtualHost *:443> section for virtual host SSL support.
See #Managing many virtual hosts for an example file.

Include conf/extra/httpd-vhosts.conf

In /etc/httpd/conf/extra/httpd-vhosts.conf set your virtual hosts. The default file contains an elaborate example that should help you get started.

Дополнительно:  Методы решения ошибки 0xc0000221

To test the virtual hosts on your local machine, add the virtual names to your /etc/hosts file:

127.0.0.1 domainname1.dom 
127.0.0.1 domainname2.dom

Restart httpd.service to apply any changes.

Managing many virtual hosts

If you have a huge amount of virtual hosts, you may want to easily disable and enable them. It is recommended to create one configuration file per virtual host and store them all in one folder, eg: /etc/httpd/conf/vhosts.

First create the folder:

# mkdir /etc/httpd/conf/vhosts

Then place the single configuration files in it:

# nano /etc/httpd/conf/vhosts/domainname1.dom
# nano /etc/httpd/conf/vhosts/domainname2.dom
...

In the last step, Include the single configurations in your /etc/httpd/conf/httpd.conf:

#Enabled Vhosts:
Include conf/vhosts/domainname1.dom
Include conf/vhosts/domainname2.dom

You can enable and disable single virtual hosts by commenting or uncommenting them.

A very basic vhost file will look like this:

/etc/httpd/conf/vhosts/domainname1.dom
<VirtualHost *:80>
    ServerAdmin webmaster@domainname1.dom
    DocumentRoot "/home/user/http/domainname1.dom"
    ServerName domainname1.dom
    ServerAlias domainname1.dom
    ErrorLog "/var/log/httpd/domainname1.dom-error_log"
    CustomLog "/var/log/httpd/domainname1.dom-access_log" common

    <Directory "/home/user/http/domainname1.dom">
        Require all granted
    </Directory>
</VirtualHost>

<VirtualHost *:443>
    ServerAdmin webmaster@domainname1.dom
    DocumentRoot "/home/user/http/domainname1.dom"
    ServerName domainname1.dom:443
    ServerAlias domainname1.dom:443
    SSLEngine on
    SSLCertificateFile "/etc/httpd/conf/server.crt"
    SSLCertificateKeyFile "/etc/httpd/conf/server.key"
    ErrorLog "/var/log/httpd/domainname1.dom-error_log"
    CustomLog "/var/log/httpd/domainname1.dom-access_log" common

    <Directory "/home/user/http/domainname1.dom">
        Require all granted
    </Directory>
</VirtualHost>

This method is probably the easiest, but is also the least scalable: it is suitable for a light request load. It also requires you to change the mpm module, which may cause problems with other extensions (e.g. it is not compatible with #HTTP/2).

In /etc/httpd/conf/httpd.conf, comment the line:

#LoadModule mpm_event_module modules/mod_mpm_event.so

and uncomment the line:

LoadModule mpm_prefork_module modules/mod_mpm_prefork.so

Note: The above is required, because libphp.so included with the package does not work with mod_mpm_event, but will only work mod_mpm_prefork instead. (FS#39218)

Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe.  You need to recompile PHP.
AH00013: Pre-configuration failed
httpd.service: control process exited, code=exited status=1

As an alternative, you can use mod_proxy_fcgi (see #Using php-fpm and mod_proxy_fcgi below).

To enable PHP, add these lines to /etc/httpd/conf/httpd.conf:

  • Place this at the end of the LoadModule list:
LoadModule php_module modules/libphp.so
AddHandler php-script .php
  • Place this at the end of the Include list:
Include conf/extra/php_module.conf

then restart httpd.service.

Using apache2-mpm-worker and mod_fcgid

This method provides improved performance and memory usage when serving multiple requests.

Install AUR and .

Create the needed directory and symlink it for the PHP wrapper:

# mkdir /srv/http/fcgid-bin
# ln -s /usr/bin/php-cgi /srv/http/fcgid-bin/php-fcgid-wrapper
/etc/httpd/conf/extra/php-fcgid.conf
# Required modules: fcgid_module

<IfModule fcgid_module>
    AddHandler php-fcgid .php
    AddType application/x-httpd-php .php
    Action php-fcgid /fcgid-bin/php-fcgid-wrapper
    ScriptAlias /fcgid-bin/ /srv/http/fcgid-bin/
    SocketPath /var/run/httpd/fcgidsock
    SharememPath /var/run/httpd/fcgid_shm
        # If you don't allow bigger requests many applications may fail (such as WordPress login)
        FcgidMaxRequestLen 536870912
        # Path to php.ini – defaults to /etc/phpX/cgi
        DefaultInitEnv PHPRC=/etc/php/
        # Number of PHP childs that will be launched. Leave undefined to let PHP decide.
        #DefaultInitEnv PHP_FCGI_CHILDREN 3
        # Maximum requests before a process is stopped and a new one is launched
        #DefaultInitEnv PHP_FCGI_MAX_REQUESTS 5000
    <Location /fcgid-bin/>
        SetHandler fcgid-script
        Options +ExecCGI
    </Location>
</IfModule>
  • Uncomment the loading of the actions module:
    LoadModule actions_module modules/mod_actions.so
  • Load the FCGID module after the loading of the unixd module (on which it is dependent) — you may wish to place this within the <IfModule unixd_module> block:
    LoadModule fcgid_module modules/mod_fcgid.so
  • Ensure that the inclusion of the MPM configuration is uncommented (it is uncommented in the default installed version of this file):
    Include conf/extra/httpd-mpm.conf
  • Add an inclusion of your new FCGID configuration:
    Include conf/extra/php-fcgid.conf

Using php-fpm and mod_proxy_fcgi

Note: Unlike the widespread setup with ProxyPass, the proxy configuration with SetHandler respects other Apache directives like DirectoryIndex. This ensures a better compatibility with software designed for libphp, mod_fastcgi and mod_fcgid.
If you still want to try ProxyPass, experiment with a line like this:

ProxyPassMatch ^/(.*\.php(/.*)?)$ unix:/run/php-fpm/php-fpm.sock|fcgi://localhost/srv/http/$1

Enable proxy modules:

/etc/httpd/conf/httpd.conf
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
DirectoryIndex index.php index.html
<FilesMatch \.php$>
    SetHandler "proxy:unix:/run/php-fpm/php-fpm.sock|fcgi://localhost/"
</FilesMatch>

And include it at the bottom of /etc/httpd/conf/httpd.conf:

Include conf/extra/php-fpm.conf

Note: The pipe between sock and fcgi is not allowed to be surrounded by a space! localhost can be replaced by any string. More here

You can configure PHP-FPM in /etc/php/php-fpm.d/www.conf, but the default setup should work fine.

Start and enable php-fpm.service, then restart httpd.service.

Test whether PHP works

<?php phpinfo(); ?>

  • While Apache supports unencrypted HTTP/2 over TCP (h2c), common browsers do not. Thus for use with the latter, #TLS must be enabled first.
  • If supporting clients do not use HTTP/2 instead of HTTP/1.1 and Mozilla’s configuration generator (which already includes the Protocols line below) was used to setup #TLS, try Includeing httpd-ssl.conf after the latter’s output.
  • Ways to test include curl -sI https://your.website or use http indicator (supports both chromium based browsers and firefox based browsers).
LoadModule http2_module modules/mod_http2.so
Protocols h2 http/1.1

To debug, you can set only the module rather than the entire server to debug or info:

<IfModule http2_module>
    LogLevel http2:info
</IfModule>

Warning: The http2_module is incompatible with the mpm_prefork_module that old configurations widely use to setup PHP. Consider using php-fpm instead.

Apache Status and Logs

See the status of the Apache daemon with systemctl.

Apache logs can be found in /var/log/httpd/

Error: PID file /run/httpd/httpd.pid not readable (yet?) after start

Comment out the unique_id_module line in httpd.conf: #LoadModule unique_id_module modules/mod_unique_id.so

/run/httpd not being created at boot

ls -la /
chown root:root /

Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe.

If when loading php_module the httpd.service fails, you may get an error like this in the journal:

Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe.  You need to recompile PHP.

This is because PHP includes support for a module that is not threadsafe, and you are trying to use a threaded MPM. One solution to fix this is to use a non-threaded MPM. Try replacing mpm_event_module with mpm_prefork_module:

/etc/httpd/conf/httpd.conf
LoadModule mpm_event_module modules/mod_mpm_event.so
LoadModule mpm_prefork_module modules/mod_mpm_prefork.so

and restart httpd.service.

Warning: Some other modules, like the http2_module, will disable themselves when mpm_prefork is active.

AH00534: httpd: Configuration error: No MPM loaded.

/etc/httpd/conf/httpd.conf
LoadModule mpm_prefork_module modules/mod_mpm_prefork.so

and restart httpd.service.

AH00072: make_sock: could not bind to address

This can be caused by multiple things. Most common issue being that something is already listening on a given port, check via ss that this is not happening:

# ss -lnp | grep -e :80 -e :443

If you get any output, stop the given service that’s taking up the port or kill the runaway process that is causing the port to be bound, and try again.

Another issue could be that Apache is not starting as root for some reason — try starting it manually and see if you still get the AH0072 error.

# httpd -k start
Listen 0.0.0.0:80
Listen [::]:80

AH01071: Got error ‘Primary script unknown’

This can be caused by ProtectHome=true in the php-fpm systemd unit file if you are serving files in /home such as in a virtual host environment. You can disable this feature by editing the php-fpm unit file and restarting php-fpm.service. Alternatively, move your document root.

Changing the max_execution_time in php.ini has no effect

/etc/httpd/conf/httpd.conf
ProxyTimeout 300

and restart httpd.service.

PHP-FPM: errors are not being logged separately per virtual host

If you have multiple virtual hosts, it may be desirable to have each of them output their error logs to separate files (using the ErrorLog Apache directive). If this is not working for you, confirm that PHP-FPM is configured to log errors to syslog:

/etc/php/php-fpm.conf
error_log = syslog
/etc/php/php-fpm.d/www.conf
;php_admin_value[error_log] = /var/log/fpm-php.www.log

Доброй зимы Вам!

Начну сразу по сути. У меня Os X Yosemite. Включил встроенный Apache и разблокировал встроенный же PHP.

При выполнении скриптов, работающих с файлами на компьютере, выскакивает ошибка доступа. Она благополучно лечится, если в папке, с которой работаю, указать права на чтение и запись (если второй требуется).
Скрипт запускаю из браузера Mozilla последней версии (хотя в Safari тоже самое).

Опытным путем было замечено, что скрипт запускается от имени Любых Пользователей. (собственно их права и переназначаю)

Отсюда суть вопроса. Как мне запускать php скрипт от имени меня, пользователя данной системы, у которого по умолчанию стоят права на чтение и запись, чтобы вручную не приходилось постоянно менять права доступа Любых Пользователей, от чьего имени запускается скрипт?
И почему он запускается от имени Любых Пользователей, ведь я его в системе запускаю через браузер вручную? (наверняка, это связано с политикой безопасности, но я пока не проникся всеми нюансами, если не сложно, кратко расскажите)

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

Заранее спасибо за ответы и теплого Вам солнца.

UPD — раскрытое решение для не посвященных

Спасибо за внимание

Добрый день господа.
Хочу поднять проект на laravel.
Создал его в: /home/rishat/workspace/web/laravelprojects/test/laravel/
Прописал в апаче локальные домены.

<VirtualHost laravel.local:80>
    ServerName laravel.local
    ServerAlias laravel.local

    ServerAdmin webmaster@localhost
    DocumentRoot /home/rishat/workspace/web/laravelprojects/test/laravel/public

    <Directory /home/rishat/workspace/web/laravelprojects/test/laravel/public>
        AllowOverride All
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Но когда пытаюсь зайти на этот адрес, выбивает.

Forbidden

You don't have permission to access / on this server.
Apache/2.4.18 (Ubuntu) Server at laravel.local Port 80
root@skeletonpc:~# sudo chmod -R 777 /home/rishat/workspace/web/laravelprojects
root@skeletonpc:~# sudo service apache2 stop
root@skeletonpc:~# sudo service apache2 start
root@skeletonpc:~#

Но прикол в том что это работает в папках где без рута никак поредачить ничего нельзя. В моем случае проект находится в папке которая не требует рута. А в итоги апач ничего не может там делать. А я могу. Даже если права через консоль даю.

Оцените статью
Master Hi-technology
Добавить комментарий