Настраиваем сервер LAMP в Mac OSX
В этом гайде мы покажем вам как настроить сервер Lamp на OSX
1. L обозначает Linux
Начнем с того, что было бы странно это называть настройкой LAMP сервера именно на Mac OSX, но все же все обычно говорят именно так. OSX фактически построен на BSD, а не на Linux. В любом случае, запомните, что буква «L» относится к операционной системе, на которой будет работать наш веб-сервер.
2. А обозначает Apache
Apache — очень популярный веб-сервер, который поставляется сразу с вашим Маком! Его легко настроить, чтобы быстро начать работу. Обязательно посмотрите команды для управления вашим веб-сервером: apachectl. Он требует root запуска, поэтому запустим его таким образом:
Основные команды для управления:
start
restart
3. М для MySQL
MySQL — очень популярная база данных с открытым исходным кодом. К сожалению, MySQL не установлена по умолчанию в Mac, поэтому вам придется установить ее самостоятельно. Я рекомендую использовать homebrew (отличный менеджер пакетов OSX) для его установки. Сначала установите homebrew. Для установки перейдите на http://brew.sh/ и следуйте инструкциям. Затем используйте homebrew для установки MySQL. Откройте — «Приложения» > «Утилиты» > «Терминал» и введите:
Теперь познакомимся с основными командами SQL:
start
restart
4. P для PHP
PHP уже установлен на вашем Mac! Это язык программирования, используемый для выполнения логических операций при вводе данных пользователем, взаимодействия с базой данных и построения ответа для отправки обратно пользователю.
5. Познакомьтесь с конфигурацией apache
Для того чтобы начать работу, никаких изменений в конфигурации не требуется, но мы немного пробежимся по теме, думаю, это будет полезно.
Вам следует найти файл конфигурации httpd.conf. httpd — это имя демона apache (не беспокойтесь, если вы не знаете, что это за демон), поэтому файл конфигурации называется httpd.conf и обычно лежит в /etc/apache2/httpd.conf.
Еще один файл, который вы хотели найти, — httpd-vhosts.conf. Это файл, в котором вы можете настроить виртуальные хосты. Виртуальный хост позволяет вам настроить несколько доменных имен для этого веб-сервера. Базовая конфигурация vhost позволяет указать имя хоста и корень документа.
Но помните, никаких изменений не требуется, чтобы начать.
6. Корень документа
Корень документа — это место, куда вы помещаете свое приложение. По умолчанию корнем на вашем Mac будет /Library/WebServer/Documents. Если вы мне не верите, откройте файл httpd.conf и найдите DocumentRoot.
7. Ваша первая веб страница
Теперь, когда мы изучили основы, мы создадим основную веб-страницу.
Используйте Finder (или терминал), чтобы перейти к корневому каталогу вашего документа /Library/WebServer/Documents. Создайте файл с именем index.php и отредактируйте его. Имейте в виду, что вам придется использовать sudo для редактирования этого файла.
Один из способов сделать это — открыть терминал и набрать:
Добавьте данный код в этот файл:
Apache будет искать исходники в корне документа, в файле index.html или index.php. Поэтому вам, возможно, придется удалить или переименовать любые другие файлы в этой папке, которые начинаются с слова index.
Теперь перезапустите веб-сервер.
Откройте браузер и введите в адресной строке:
И вот, открылась наша веб-страница, немного скучная, поскольку показывает только текущую дату, но для начала нам хватит и этого.
Lamp mac os x
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Laptop is a script to set up an OS X laptop for web development (LAMP).
It can be run multiple times on the same machine safely. It installs, upgrades, or skips packages based on what is already installed on the machine. Unfortunately we need some sudo commands for apache config, so the script might ask for your password to use sudo.
Thanks guys for all the hard work and inspiration for me to create my own version.
The script will aim to create an development environment inside this folder: /User/USERNAME/Sites/ .
Every folder you create inside can be accessed through .mac domain. The apache config supports three levels of folders that can be accessed.
- my-new-site.mac => /User/USERNAME/Sites/my-new-site/
- site.client1.mac => /User/USERNAME/Sites/client1/site/
- other-site.client2.mac => /User/USERNAME/Sites/client2/other-site/
- public.other-site.client2.mac => /User/USERNAME/Sites/client2/other-site/public/
Note: To access phpMyAdmin append /phpmyadmin at the end of the url. Username is root with no password.
- OS X Mavericks (10.9)
- OS X Yosemite (10.10)
- OS X El Capitan (10.11)
Older versions may work but aren’t regularly tested. Bug reports for older versions are welcome.
Download and execute the script (As your normal User):
Note: You will be asked to type in your password to use sudo command.
Your last Laptop run will be saved to
/laptop.log . Read through it to see if you can debug the issue yourself. If not, copy the lines where the script failed into a new GitHub Issue for us. Or, attach the whole log file as an attachment.
OS X El Capitan (10.11)
You may have problems installing Homebrew for the first time on OS X El Capitan due to permission changes to the /usr directory (within which the Homebrew installation is typically located). See the Homebrew El Capitan troubleshooting instructions for steps to resolve the permissions issues that interfere with Homebrew’s installation.
If your .mac domain doesn’t work try setting the Dnsmasq service to run with root privileges.
- Git for managing git repositories
- Homebrew for managing operating system libraries
- ImageMagick for cropping and resizing images
- Node.js and [NPM], for running apps and installing JavaScript packages
- Mysql for storing relational data
- Ruby stable for writing general-purpose code
- Dnsmasq to configure .local domain
- Phpmyadmin for managing mysql databases
- Grunt to run automated tasks
- Gulp to run automated tasks
- Sass to extend CSS for your projects
- Compass to add additional funcions and mixins to Sass
- Less as an alternative to Sass
- Svgo tool for optimizing SVG
- Bower web package manager
- Brew Cask to install tools and link them to your Applications folder
Tools (using brew cask)
- LaunchRocket — launchd management
- Google Chrome — browser
- Firefox — browser
- Source Tree — GIT client
- FileZilla — FTP client
- Sublime Text — Text Editor
- Sequel Pro — DB management
It should take less than 30 minutes to install (depends on your machine and connection speed).
What files it will create and change
Changes to /private/etc/apache2/httpd.conf
- Uncomment #LoadModule php5_module
- Uncomment #LoadModule vhost_alias_module
- Uncomment #LoadModule rewrite_module
- Change user User USERNAME
- New line Include /private/etc/apache2/users/*.conf
Changes to /private/etc/apache2/users/USERNAME.conf
Contents of this file will be replaced by following config:
Changes to $(brew —prefix)/share/phpmyadmin/config.inc.php
New files for .mac domain set up
- $(brew —prefix)/etc/dnsmasq.conf will contain address=/.mac/127.0.0.1
- /etc/resolver/mac will contain nameserver 127.0.0.1\ndomain mac\nsearch_order 1
- /Users/USERNAME/Sites/test/index.php will contain to check if the .mac domain is working: test.mac
/.laptop.local is run at the end of the Laptop script. Put your customizations there. For example:
Write your customizations such that they can be run safely more than once. See the mac script for examples.
Laptop functions such as fancy_echo , brew_install_or_upgrade , and gem_install_or_update can be used in your
Edit the mac file. Document in the README.md file. Follow shell style guidelines by using ShellCheck and Syntastic.
Laptop is © 2015 TNT-IT ltd. It is free software, and may be redistributed under the terms specified in the LICENSE file.
About
Apache, MySQL, PHP envionment + front / back developer tools for Max osx
A Guide to Native LAMP Stack in Mac OS X
Are you using MAMP Pro for web development? Has it ever caused you to drink heavily while simultaneously banging your head against the keyboard? Follow this guide, and you will never have to experience the horror that is the MAMP stack again!
Don’t get us wrong – MAMP was great for a while. Convenient even. It had this nice little button labeled “Start”, and then it would turn green when it was ready. It handled all those pesky VHosts and hosts file entries for me. Then one day, out of nowhere, it reared its ugly head when I had the audacity to try to use the ImageMagick extension for PHP.
This is the fly in the ointment when it comes to MAMP. It lives off in its own little world on your computer, oblivious to the endless stream of change in the real world of web development. It is an added layer to the already complex set of layers standing between your keyboard and a web application. It eats memory like a pig, has a hard time following directions, and does not play nice with others.
So, what to do? First, a disclaimer: the following guide is what you would call an ‘overhaul’ of your development environment. It can be fraught with peril – and subsequent triumph – for the determined soul. In other words, it may take you longer than you like to get back up and running. Plan accordingly.
Backup and cleanup
Dump and backup databases from MAMP’s environment:
Get all databases (grab a beer and a sandwich, this could take a while):
Note that this will dump “ALL” databases into a single file. If you want to be up and running quickly with specific sites, try the next command instead. Also, this does not preserve users and permissions. So if you use a separate user/password for each of your databases, make sure you know what those are / how to set them up later.
Or, if you prefer, just grab the ones you need one at a time:
- Backup /Applications/MAMP/htdocs (your websites!)
- Remove MAMP Pro (drag to trash)
- Delete MAMP from your system path
If you see any MAMP related thing in your path, find it and remove it. Usually, this will be a line in your bash profile.
- Edit /etc/paths (with your favorite editor!):
Add /usr/local/bin to the first line. This will make sure that packages installed with Homebrew are the first thing in your path.
Now close this terminal window and open a new one. This will update your environment with the new path.
- Install Homebrew (if you haven’t already):
Normalize Homebrew (if already installed):
Fix any errors. (DO NOT SKIP THIS PART!) Usually these errors have to do with your path, or extraneous files and libraries in /usr/local, or brew not finding Mac OS System libraries where it expects them to be. There is a wide range of errors that occur, and this step can take some time, and some serious googling. Also, make sure you run:
Install lunchy (for starting and stopping daemons):
A Side Note about daemons
Mac OS X relies on launchctl to start and stop services. It is similar to init.d in linux, or service in Ubuntu. lunchy is a wrapper for launchctl. It makes it easier to start and stop services. Services that are owned by root have init scripts in /Library/LaunchDaemons. To start and stop these services using lunchy, you must use sudo. Services owned by the user have init scripts in
/Library/LaunchAgents/. Lunchy does not require sudo to start and stop these services.
Install Packages using Homebrew
$ brew install php53-xdebug – There are a smorgasbord of extensions to choose from:
- php-code-sniffer
- php53-apc
- php53-imagick
- php53-memcached
- php53-mongo
- php53-redis
- php53-uploadprogress
- php53-xdebug (recommended)
- php53-xhprof
These extensions are completely optional and can be installed at any time. You can always run a brew info package_name, and check out the web link for more info on each extension.
- Edit php.ini (xdebug settings & memory limit)If you like to use memory hungry PHP frameworks like Drupal, you will need to up the memory limit for PHP scripts.
$ emacs /usr/local/etc/php/5.3/php.iniSearch for memory_limit and set it to 2048M
MariaDB (MySQL)
MariaDB is an optimized fork of MySQL. It works great as a drop-in replacement for the standard version of MySQL. If you would rather not use MariaDB you can do all of these same steps, just replace the word mariadb with the word mysql.
Setting up Apache
Mac OS X has the Apache webserver built-in. Let’s make it play nice with our newly installed PHP module.
Add the following line at the end of the LoadModule section:
Now we can restart apache:
Setting up VirtualDocumentRoot
Apache allows for a wildcard to be used when specifying the document root. The implications of this are that you can create a directory, and apache will treat that directory as if it were a VirtualHost. No more creating separate VHosts for every project!
It can help to create a config file for the OS X user:
This sets up Apache to serve your projects from the Sites folder inside your home directory. Apache will serve files from the htdocs folder, so websites will be stored on your local filesystem here:
There is one other configuration setting that is nice to have:
Find the ServerName directive and change it to:
This will suppress the warning about apache not being able to resolve a fully qualified domain name. Now restart apache.
From there, simply check that all is well.
Note: if you haven’t actually created a
/Sites/project directory yet, you may get a warning here:
Note that when using VirtualDocumentRoot, any site that is using RewriteRules to route all requests through a front controller (index.php), you will have to set RewriteBase / in .htaccess.
On Mac OS X, apache runs under the user _www. There is also a group called _www. Your project’s htdocs folders should have permissions set accordingly.
Setting up DNS
Now that Apache is all set up, we need an easier way to point our project names to localhost so that we can type something like projectname.dev in a browser. You could easily do this by adding lines to /etc/hosts, but that is tedious manual labor, and I will not stand for it.
Setup the config file for dnsmasq:
Dnsmasq is a caching DNS server that runs locally and handles DNS requests. We just set it up to send all requests ending in .dev to localhost. Now we just need to tell Mac OS to use dnsmasq instead of the DNS server that is assigned to you by your gateway. The most straightforward way of doing this is to simply add 127.0.0.1 to your list of DNS servers. The problem is that you will also need to make sure that you have another DNS server for other requests. I like to use OpenDNS.
Navigate to System Preferences -> Network -> WiFi (or your most used network interface) Click Advanced, and go the DNS tab. Under DNS servers, add 127.0.0.1 at the top of the list, followed by 208.67.222.222 (or any other nameserver).
There is a way to do this automatically with some scripting. This works well if you are always using different wireless networks and such.
Once DNS is set up, you should be able to:
and get a response from 127.0.0.1
That’s it! Now you can put your sites back into the sites directory you defined in your apache configuration, restore your databases, and you are off to the races. Happy coding!