Меню Рубрики

Restart apache mac os

Mac OS x Restart Apache Web Server

H ow do I restart Apache web server under Mac OS X operating systems?

The apachectl command act as Apache HTTP Server control interface. It can be used to start, stop, and restart the Apache web server from command line.

Open a terminal and type any one of the following command:

sudo apachectl restart

sudo apachectl -k restart

Fig.01: Restarting Apache under Mac OS X

Task: Stop Apache Web server

sudo apachectl -k stop

Task: Start Apache Web server

sudo apachectl -k start

Thanks, but it might be easier this way: Open the “Sharing” preference, (de-)select “Web Sharing”.

I was just wondering if OS X got some sort of service manager. I need to dig it a little more…

thanks for the comment!

The software to start/stop (load/unload) services is called “launchctl”. From the man page:

launchctl interfaces with launchd to load, unload daemons/agents and generally control launchd. launchctl supports taking subcommands on the command line, interactively or even redirected from standard input.
These commands can be stored in $HOME/.launchd.conf or /etc/launchd.conf to be read at the time launchd starts.

Vivek, what does the -k switch do? I couldn’t find it in the man page for apachectl on a Mac OS X system.

@Robert, I will look into it.

@Leaman, the apachectl command works in two modes:
a) Sys v style mode – One line command mode which take args like start, restart, and stop, and translating them into appropriate UNIX signals to httpd.

b) Traditional UNIX mode with lots of options for testing and debugging. In this mode it can act as a simple front-end to the httpd command that simply sets necessary environment variables and then invokes httpd, passing through any command line arguments.

it does’mt work for me 🙁

sumitgupta$ apachectl -k graceful
httpd: Syntax error on line 488 of /private/etc/apache2/httpd.conf: Syntax error on line 8 of /private/etc/apache2/other/+entropy-php.conf: Cannot load /usr/local/php5/libphp5.so into server: dlopen(/usr/local/php5/libphp5.so, 10): Symbol not found: _libiconv\n Referenced from: /usr/local/php5/lib/libintl.8.dylib\n Expected in: /usr/lib/libiconv.2.dylib\n
SUM-IT:

this is the problem i am facing please help…..

i receive an error when I try to restart apache with: sudo apachectl restart
the error reads: /urs/sbin/apachectL: line 73: unlimit: open files: cannot modify limit: invalid argument

can anyone help! please.

changes are to be made in “/usr/sbin/apachectl”

comment out the these lines.

i did this through the command line using ‘vi’ commands

@Javier, I’d say there is an error in your httpd.conf file. Open it up in the plain-text editor of your choice–one that shows line numbers–and look at line 73. There is either a syntax error or an invalid argument for the option contained on that line.

lemanc,
i went to httpd.conf file and line 73 is ‘LoadModule include_module libexec/apache2/mod_include.so ‘ do you know anything about this kind of issue?
thanks in advanced!

This is not the correct solution. Please see my other reply for the solution.

Источник

Is there a way to automatically restart Apache on Mac OS X if it crashes?

I’ve installed Apache using MacPorts. It crashes every once in a while, and I need to manually restart it.

Is there a way to get Apache to automatically restart if it dies for some reason? Perhaps using launchd somehow?

1 Answer 1

Use launchd to start Apache, and make Apache run in the foreground so launchd can monitor it and restart it if it crashes. Since the system includes a launchd item ( /System/Library/LaunchDaemons/org.apache.httpd.plist ) to start the built-in version of Apache, I’d just copy that to /Library/LaunchDaemons , change the filename and Label so launchd won’t get them confused, remove the Disabled key, and change ProgramArguments to point to the MacPorts version of Apache. Be sure to keep the -D and FOREGROUND arguments to httpd , or it’ll daemonize itself and launchd will start another instance and nothing useful will get done.

(And do follow @RedGrittyBrick’s advice about finding the actual cause of the crash. While launchd is the «right» way to start a daemon like Apache on Mac OS X, it’s just a band-aid for whatever problem Apache is having.)

Источник

Установка и настройка Apache в MacOS 10.15 Catalina

Предварительные условие для инструкции:

После выполнения предварительных условий начнем с установки некоторых зависимостей для Catalina:

Последняя версия MacOS 10.15 Catalina поставляется с предварительно установленной версией Apache 2.4, однако использовать эту версию вместе с Homebrew не правильно, поскольку Apple удалила некоторые необходимые скрипты в этом выпуске. Решение состоит в том, чтобы установить Apache 2.4 через Homebrew, а затем настроить его для работы на стандартных портах (80/443).

Если у вас уже работает встроенный Apache, сначала его необходимо отключить и удалить все сценарии автозагрузки. На самом деле будет полезно просто запустить все эти команды по порядку — даже если это новая установка:

Теперь установим новую версию Apache которая поставляется по средствам Brew:

Теперь выполним команду которая позволит нашему серверу запускаться в автоматическом режиме:

Все, вы установили Apache Homebrew и настроили его на автоматический запуск с привилегированной учетной записью. Сервер уже должен быть запущен, проверить это можно пройдя по ссылке http://localhost:8080, вы должны увидеть простой заголовок с надписью «It works!».
Apache управляется с помощью команды apachectl, ниже указаны некоторые команды которые будут полезны:

Конфигурация Apache.

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

В последней версии Brew вы должны вручную установить порт прослушивания по умолчанию от 8080 до 80, поэтому нам нужно будет отредактировать файл конфигурации Apache

Также мы должны включить mod_rewrite, который закомментирован по умолчанию. Найдите в файл mod_rewrite.so и раскомментируйте строку, удалив первый символ ришотки #:

Теперь у нас есть конфигурация Apache, указывающая на папку Sites в нашем домашнем каталоге. Однако одна проблема все еще существует. По умолчанию apache запускается как пользовательский демон и демон группы. Это приведет к проблемам с правами доступа при попытке обращения к файлам в нашем домашнем каталоге. Примерно на треть вниз по файлу httpd.conf есть две настройки, под которыми будет работать пользователь и группа Apache. Их нужно изменить таким образом, чтобы они соответствовали вашей учетной записи пользователя и группе (потребуется заменить your-user на ваше реальное имя пользователя) :

где «your-user» имя ваше пользователя в системе.

Теперь нам нужно создать папку Sites в корне домашнего каталога вашего пользователя. Это можно сделать сделать это в терминале или в Finder. В этой новой папке «Sites» vs мы создадим простой файл index.html и напишем там что-то что будет показывать, что это именно папака пользователя, например:

My User Sites Folder .

После этого перезапускаем Apache командой:

Теперь при казании в адресной строке вашего браузера http://localhost должен отобразится наш текс из шага ранее — My User Sites Folder.

Если вы видите это, значит вы все сделали правильно и теперь Apache по умолчанию смотрит в папку Sites вашего пользователя.
На этом первичную настройку Apache можно считать законченой.

Источник

Start an Apache Web Server in Mac OS X El Capitan, Mavericks, & Mountain Lion

The Sharing preference panel options were changed a bit in OS X Mountain Lion and again in Mavericks, and while things like Internet Sharing remain, the Web Sharing preference panel was removed. The Apache web server remains bundled with Mac OS X though, but you’ll need to turn to the command line to enable the web server. Additionally, you’ll want edit a user configuration file for each user account on the Mac to have the personal web sharing feature active. If any of this sounds intimidating or complex, it’s really not, just follow along and you’ll have a simple web server running on your Mac in no time.

Setting Up and Starting the Apache Web Server in OS X

Versions of OS X prior to El Capitan, Yosemite, Mavericks, Mountain Lion and Mavericks can simply turn on “Web Sharing”, but from 10.8, 10.9, 10.10, and 10.11 onward you’ll need to do the following to use a local web server:

  • Launch Terminal, located in /Applications/Utilities/
  • Type the following command, replacing USERNAME with the user account short name:

Enter the admin password when requested, then paste the following into the nano text editor:

Options Indexes Multiviews
AllowOverride AuthConfig Limit
Order allow,deny
Allow from all

In the .conf file it will look like this:

  • Edit the Directory path USERNAME to the appropriate username
  • Now hit Control+O to save the changes to USERNAME.conf, then hit Control+X to quit out of nano
  • Next, you will start the Apache web server with the following command:

    sudo apachectl start

  • Launch Safari, Chrome, or Firefox and navigate to “http://127.0.0.1” to verify the server is running, you will see an “It Works!” message
  • Now that you’ve started a successful Apache server in OS X, you can either modify the core ‘localhost’ files, or go further with the user files.

    Apache Web Server Documents Location & User Sites Folders

    Note, if you just want to use and modify ‘localhost’ root and not the user level Sites at localhost/

    user, you can find the apache webserver files and ‘It Works!’ html in the following location:

    You can now also visit http://127.0.0.1/

    USERNAME/ to see the contents of whatever is stored in the user

    /Sites/ directory – if anything is there per user – and you can add an index.html file or whatever else you’d like to the directory to serve it to the outside world or even just your LAN.

    Using http://localhost/ is also fine, and by editing the hosts file you can set a local domain to whatever you want to create a local test environment with an otherwise live domain.

    This whole process is quite fast, and can be completed in under a minute as demonstrated in the video walkthrough below:

    Shutting Down Apache & Restarting Apache Server

    To shut down the web server, go back to the command line and type the following:

    sudo apachectl stop

    If you make changes to the server and just want to restart it, that can be accomplished with the following command instead:

    sudo apachectl restart

    The default Apache server is barebones and does not have PHP, MySQL, or anything particularly fancy enabled. You can either install and configure those manually, or you can go the pre-configured route through an all-in-one server app like MAMP, which includes Apache, MySQL, and PHP in a simple to control app-based web server package. You can get MAMP free from here.

    Thanks to Ben for the tip idea

    Related

    Related articles:

    65 Comments

    After upgrade from Yosemite to High Sierra, I got 404 not found on a localhost user directory, although plain localhost gave “It Works!” as it should. Fix for me was the answer by Hesham (first of six as of 1/19/2018) at StackOverflow

    What worked for me after upgrading from El Capitan to Sierra as well:

    1) Uncommenting from /etc/apache2/httpd.conf

    LoadModule userdir_module libexec/apache2/mod_userdir.so
    LoadModule vhost_alias_module libexec/apache2/mod_vhost_alias.so
    Include /private/etc/apache2/extra/httpd-vhosts.conf
    Include /private/etc/apache2/extra/httpd-userdir.conf
    2) Uncomment from /etc/apache2/extra/httpd-userdir.conf

    Include /private/etc/apache2/users/*.conf
    3) In my /etc/apache2/users/$USERNAME.conf file I had ProxyPass configured as well, and to get it working again I had to re-uncomment the following from my httpd.conf

    LoadModule proxy_module libexec/apache2/mod_proxy.so
    LoadModule proxy_http_module libexec/apache2/mod_proxy_http.so
    4) Optional for PHP: You need to re-uncomment the following from the httpd.conf as well:

    LoadModule php5_module libexec/apache2/libphp5.so
    5) Of course, restart apache

    sudo apachectl -k restart
    Things worked for me afterwards

    What i do not understood is if truth be told how you’re no longer actually much more smartly-liked than you might
    be right now. You’re very intelligent. You know thus considerably in the case of this topic, made me in my opinion imagine it from
    so many varied angles. Its like women and men are not involved unless it is something to do with Lady
    gaga! Your individual stuffs nice. Always maintain it up!

    OK I’m all fixed. Saw my errors and deleted the files I created accidentally manually. Thank God you can still get to the etc directory that way.

    I used this text for 10.8.3 instead of what I saw here and in https://www.youtube.com/watch?v=aEE6ZIonBoM where he’s doing it for 10.11 but had the clearest explanation which I followed to success.

    …and then I fixed the user.conf file and the Sites folder permissions with command-i, because before that it would not let me edit a file in the Sites folder. Now my php sites show up, and it does allow me to edit .php files. I just have to get that control panel back to turn on and off the Sharing without having to use Terminal

    Options Indexes MultiViews
    AllowOverride All
    Order allow,deny
    Allow from all

    But if you cannot be allowed into the /etc/ you are screwed. Don’t know how I got into it on 10.6.8 because it won’t let me there. However, Sites folder and Web Sharing were GUI back then.

    Basically what you are doing is—

    1) You can turn the server on and off in the terminal even if you are a newb at using it and old lady like me (later you put the control panel add-on but mine wasn’t working so I took it off) That’s the first step.

    2) You can get to the /etc/ file manually, but you won’t be able to save changes after erasing the #s, so you need to use the terminal to uncomment your PHP, PERL or whatever other modules you need.

    3) You need to create a SITES folder in your HOME(House) directory because after 10.6.8 they don’t include one, but the tricky part was writing that stuff above into the terminal to make it connect with your localhost/

    username and bring up that page with your sites in it.

    4) I then fixed permissions manually using Get Info

    Hit or miss but I did it.

    For OS X El Capitan and OS X Yosemite, the above works as now to start apache server, but it will enable the root localhost directory only. To get the USER LEVEL “Sites” folders working, so that you can visit ‘localhost/

    username’ in the browser for each user account on the Mac, you need to modify the apache configuration in OS X 10.10+ and 10.11+ further as so:

    Uncomment the following:

    LoadModule userdir_module libexec/apache2/mod_userdir.so

    Then in http-userdir.conf you need to uncomment:

    Lastly you would need to create /private/etc/apache2/users/NAME.conf if it doesn’t exist.

    I think it should look something like this:

    Options Indexes MultiViews
    AllowOverride None
    Require all granted

    Then restart Apache again. Boom, browser point to localhost/

    USERNAME and it will load

    sudo apachectl restart

    Boom, Apache running at the user “Sites” folder

    Yes! Thank you. I had gotten through everything except the “Require all granted” line that needed to replace the previous “Order / Allow” lines.

    Thanks mate! This sorted out Internal Server error.

    Hello,
    I am planning to run Apache WebServer on my Macbook OS X ver 10.10.2.
    However, when I try to edit the file /etc/apache2/users/USERNAME.conf
    I get error message
    I have logged in as admin user and the USERNAME substituted is also the same as the admin user

    else you will have “404 not found”.

    Everything was fine until I got to the sentence “to see the contents of whatever is stored in the user

    /Sites/ directory” which makes no sense since there is no directory with that name anywhere on my computer. Did I miss something? This page also neglects to mention where the “It Works!” text comes from. I searched my entire hard drive, I was unable to find any such text. perhaps I’m having the same problem as David, who posted one day before me.

    The “It works!” text is located in /Library/WebServer/Documents for me (running Yosemite). The path is defined in /etc/apache2/http.conf.

    Could someone explain how the apache web server is allowing me to access files in my sites directory or take a look at how I am trying to access them now? I have the server running, but am having difficulty displaying test web pages in my sites directory.

    For instance, if I am trying to display index.html, I receive a “Not_Found” error when I try to access it with any of these path names.

    As a note, I have tried stopping and restarting the server

    have you checked the permissions of the index.html file?

    sudo chmod a+rx index.html

    The tutorial should mention that you need to enable (uncomment) the following lines:

    1) Open/Edit file “/etc/apache2/httpd.conf”
    2) Uncomment line “LoadModule userdir_module libexec/apache2/mod_userdir.so”
    3) Uncomment line “Include /private/etc/apache2/extra/httpd-userdir.conf”

    4) Open/Edit “/etc/apache2/extra/httpd-userdir.conf”
    5) Uncomment line “Include /private/etc/apache2/users/*.conf”

    Right, that is to set up and start the Apache server in OS X Yosemite, did you try it?

    Just got this working for my wife on Yosemite. I had to do what John commented above. Furthermore, due to the version of Apache being greater than 2.4.3, I had to add the following directive to my Directory block:

    Require all granted

    I also had to change to: AllowOverride None
    I was getting an internal server error when AllowOverride was:
    AllowOverride AuthConfig Limit
    I’m guessing this is due to NOT having a .htaccess file in the directory. There was an error message in the apache log file that stated, “…Sites/.htaccess: Options not allowed here”.

    So, the directory block now looks like:

    Options Indexes Multiviews
    AllowOverride None
    Order allow,deny
    Allow from all
    Require all granted

    I’m still not certain this is all correct. It works for, but I’d do a lot more investigation if this wasn’t just for home use.

    I tried this on 10.8.5 and it didn’t work. I got the following page:

    Forbidden
    You don’t have permission to access /

    jrb/ on this server.

    Ok, why is this I wondered. Where is apache writing its log file, that might tell me. So I did this from a Terminal:

    jrb$ cd /etc/apache2/
    lily:apache2 jrb$ grep ErrorLog httpd.conf
    # ErrorLog: The location of the error log file.
    ErrorLog “/private/var/log/apache2/error_log”

    Ok so now I know where the log file is, lets have a look at the last few lines:

    lily:apache2 jrb$ tail -5 /private/var/log/apache2/error_log

    [Sat Sep 13 19:04:31 2014] [error] [client 127.0.0.1] (13)Permission denied: access to /

    jrb/Sites denied (filesystem path ‘/Users/jrb/Sites’)

    From this I can see I wrote my jrb.conf file correctly because apache is saying it can’t access ‘/Users/jrb/Sites’ which it got from the

    jrb url. Maybe this is just a file system problem? Turns out it was.

    The web server runs as the user and group set in httpd.conf. What is that? Again from the Terminal

    lily:apache2 jrb$ grep User httpd.conf
    # User/Group: The name (or #number) of the user/group to run httpd as.
    User _www

    So there is a user id that OSX has been set up with called _www for the sole purpose of running Apache. Maybe that user id can’t see my Sites folder? Lets find out, the sudo command takes a -u option that’ll let to specify any user (not just the super user):

    lily:apache2 jrb$ sudo -u _www ls /Users/jrb/Sites
    Password:
    ls: /Users/jrb/Sites: Permission denied

    Aha! This is probably why I’m getting that error, at any rate apache will not be able to serve files in my Sites directory before this works.

    Lets see what the permission are on my home folder:

    lily:apache2 jrb$ ls -l /Users
    total 0
    drwxrwxrwt 13 root wheel 442 Apr 11 15:35 Shared
    drwx—— 131 jrb staff 4522 Sep 13 19:00 jrb

    This will be very familiar to UNIX/Linux users but not mean much to anyone else but the 6 ‘-‘ chars after rwx mean that anyone other than me on this machine can not look inside the ‘jrb’ folder. I’m not going to try to explain that or why the next command will fix it but what I’m going to do is add read and execute permission to both the staff group and anyone else (other)

    lily:apache2 jrb$ chmod go+rx /Users/jrb

    Let’s check that did the right thing:

    lily:apache2 jrb$ ls -l /Users
    total 0
    drwxrwxrwt 13 root wheel 442 Apr 11 15:35 Shared
    drwxr-xr-x@ 131 jrb staff 4522 Sep 13 19:00 jrb

    Yes, the last three – changed to r-x, that’s for “others” and the 3 before that did also, that’s for the “staff” group.

    Now let’s see if apache can not read my Sites folder:

    lily:apache2 jrb$ sudo -u _www ls /Users/jrb/Sites
    Password:
    images index.html iwebtest

    jrb/ work? Yes, yes it does. Phew. OSX put that index.html file in there (and images and iwebtest) to let you know apache is working. You can delete them and start putting your own stuff.

    Nope. Like everything in the $%^* open source world it just DOESN’T work. I have tried a dozen times, created a Sites directory, changed Administrator permissions to allow read/write access to the normal user directory – still just get access forbidden…

    I run a user account WITHOUT admin permissions – for obvious reasons. This means logging in and out of the user and Administrator account every time I try this.

    I had similar problems a few years ago trying to get Ruby On Rails working – I did, eventually, but it took an age.

    And, of course, in the meantime you are working in the most user-unfriendly environment imaginable – deep under the hood of the operating system which turns Unix into something a sane person would buy.

    I cannot imagine why Apple do not take this in hand and put a proper front end on all this sh*t from the open source world so you can just press a button and install it, like everything else in the Mac environment.

    I note that many of the users on here who got this to work had to make changes – and not the same ones.

    Upgraded (Mac OS 10.4) Apache1.3 site to Apache2 (10.8). Uhhhhgggg! What a pain.

    @Torbin thank you for the tip: httpd -t saved me so much time. Really did not feel like digging into my conf files to figure out what the syntax errors were.

    thumbs up! it works perfectly. easy tutorial

    I hit some confusion regarding the “users”-directory, isn’t the same reference used to the apache folder and later to the home folder? I went mamp and noticed the reference to the home folder afterwards.

    I hit some confusion regarding the “users”-directory, isn’t the same reference used to the apache folder and later to the home folder? I went mamp and noticed the reference to the home folder afterwards.

    Oո peut vous dire que ce n’est nullement absurde …

    I got 403 Forbidden, You don’t have permission to access this server. Please any solution to fix thing problem

    I’m a bit new to this so please excuse my ignorance. I was wondering how I would go about adding my index.html page to the server. Do I add it through nano?

    This worked perfectly except that i needed to make the “Sites” folder. I just wondered if it is possible to show the index.html file without entering a user?

    Well looks like 10.83 broke Apache again. I normally do everything in this webpage with each update and now I get a “Forbidden: You don’t have permission to access / on this server”. The nearest I can figure is that the 10.83 update has munged permissions somewhere. Apple really needs to get on the ball with this – apache on OS X used to be the most painless thing I can imagine and now it’s some of the most painful. Ideas?

    I was able to confirm that Apache still works in OS X 10.8.3, make sure you have everything configured properly and use sudo to launch apache:

    sudo apachectl start

    If you’re encountering permissions errors, you can also try to point apache at a different directory with the -d flag:

    sudo apachectl start -d /Path/To/Directory/

    For someone who is having this problem today, usually this is because you don’t have “Sites” directory under the current user.

    Go to finder, Commmand+Shift+G and you get the full file system access. Navigate to /users/currentuser/ and create a “sites” directory.

    Jeez, this is the first time I’m doing mac development and I almost it up to this silly issue. I’m only hopeful there won’t be many stupid ones like this.

    and what about http sharing not only localhosting ??

    Источник

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Resizer image mac os
  • Reset password mac os sierra
  • Remove php mac os
  • Remoteapp на mac os
  • Remote desktop connection для mac os