Tran Nghi's Site  - Make notes and share experience

How to give a user permission to restart apache?

This post is also available in: English

1. Short answer

Using visudo, add the following to your sudoers file, replacing username with the proper username:

username ALL = /etc/init.d/apache2

If you want to not have to type in a password before you do this, use the following:

username ALL = NOPASSWD: /etc/init.d/apache2

After this, the ‘username’ user can execute sudo /etc/init.d/apache2 start (or stop, restart,etc)

Regarding to /etc/sudoers, please refer to this topic Sudoers – Give a user permission to login as another user

2. Long answer

You’ll likely want to setup a separate user for this if you haven’t already, and then configure the /etc/sudoers file to allow a user or group to execute the command you want.

For example:

## allow a user to execute all commands as root, prompting for a password, do the following:
username ALL= ALL
## allow a user to execute only one command (like say, rm), do the following:
username ALL= /bin/rm
## allow user to run a script without prompting for a password, use the ‘NOPASSWD’ option like so:
username ALL= NOPASSWD:/bin/commandname options
## you can do the same thing for groups by prefixing group names with a percentage sign, like so:
%supportstaff ALL= NOPASSWD:/bin/commandname
## allow a user to exclude “service” command, to reload/start/stop/restart a service, like so:
username ALL= NOPASSWD:/usr/sbin/service

3. Tips & Tricks

3.1. Create a new users:

sudo useradd -m -s /bin/bash <username>

3.2. Set password for user:

sudo passwd <username>

3.3. Add user to a group
(ie. you may want to add a user to sudo group, in order to let that user exclude command as root):

sudo usermod -aG <groupname> <username>

3.4. Remove user from a group
(ie. you may want to remove a user from sudo group, in order to stop/prevent that user no longer exclude command as root):

sudo deluser <username> <groupname>

Message