Thursday, July 10, 2014

How to configure SSL under Apache 2 + Laravel

Quick tips on how to setup SSL under LAMP stack + Laravel 4.2 PHP framework.

We need to get certificate itself. In order to run your webpage through HTTPS protocol, we will need 3 files:

  1. SSL certificate private key file (.key)
  2. Certificate Signin Request (.csr)
  3. SSL certificate file (.crt)
  4. SSL chain file (.ca-bundle)

This extensions (.key .crt etc.) can differ. In different guides i saw different extensions, like .pem or .ca, so dont worry about that.

1st and 2nd file we will generate on our server machine; 3rd and 4th file we will get from certification service.

So lets start! We need to open terminal and paste commands below (commands will be explained):

1. cd ~/Documents/SSL
SSL is a custom folder created by me. You can store your certification files wherever you want, I used path above.

2. sudo openssl genrsa -des3 -out private.key 2048
Generating "private.key" file with 2048 bit encryption. We will need this to generate our CSR (2nd file) and later, when we will setup apache virtual hosts.

3. sudo openssl req -new -key private.key -out server.csr
Generating "server.csr" file in order to get our certificate. While this step You will need to fill in some information, that system will request you:

Country Name (2 letter code) [AU]: EE
State or Province Name (full name) [Some-State]: Harjumaa
Locality Name (eg, city) []: Tallinn
Organization Name (eg, company) [Internet Widgits Pty Ltd]: Your Company Name Ltd
Organizational Unit Name (eg, section) []: IT
Common Name (eg, YOUR name) []: www.yourdomain.com
Email Address []: youremail@gmail.com
A challenge password []: (you can leave it blank)
An optional company name []: (you can leave it blank)

Of course you can edit all those fields as you want.

4. Now we'r going to http://www.comodo.com/e-commerce/ssl-certificates/free-ssl-certificate.php and registering our certificate. In order to get certificate, you will need to provide CSR, that we already generated. Opening server.csr with, for example, nano sudo nano server.csr (or gedit, or vim, or download it through filezilla etc.) and copy text in server.csr. It should look like:

-----BEGIN CERTIFICATE REQUEST-----
MIIDUDCCArkCAQAwdTEWMBQGA1UEAxMNdGVzdC50ZXN0LmNvbTESMBAGA1UECxMJ
TWFya2V0aW5nMREwDwYDVQQKEwhUZXN0IE9yZzESMBAGA1UEBxMJVGVzdCBDaXR5
(more encoded data).......
Rq+blLr5X5iQdzyF1pLqP1Mck5Ve1eCz0R9/OekGSRno7ow4TVyxAF6J6ozDaw7e
GisfZw40VLT0/6IGvK2jX0i+t58RFQ8WYTOcTRlPnkG8B/uV
-----END CERTIFICATE REQUEST-----
In "Select the server software used to generate the CSR" field choose Apache-ModSSL (if you use LAMP stack, of course).

In "Select the hash algorithm you would prefer us to use when signing your Certificate" choose anything you want.

Complete the registration. You will need to confirm your domain, because of that confirmation will be sent one one of your domain emails (like admin@yourdomain.com or webmaster@yourdomain.com).

When you will totally complete registration, certificate will be sent to your email in zip archive. This archive will contain 2 files: certificate file (.crt) and chain file (.ca-bundle). Dont ask me, why we need this .ca-bundle, just google it :)

5. Upload this 2 files on your server certificate directory (for me it was ~/Documents/SSL/)

6. Edit your apache virtual host, as now we'r going to use secured connection. You will need to create new secured virtual host:
sudo cp /etc/apache2/sites-available/example.conf /etc/apache2/sites-available/yoursite.com.secured.conf
I dont actually remember name of the example.conf file, but you need to create copy of the virtual host, or just create new one with touch /etc/apache2/sites-available/yoursite.com.secured.conf

7. Add inside <VirtualHost> tag instuctions below, and dont forget to change virtual host port to 433:
SSLEngine on
SSLCertificateFile /home/ubuntu/Documents/SSL/your_domain.crt
SSLCertificateKeyFile /home/ubuntu/Documents/SSL/private.key
SSLCACertificateFile /home/ubuntu/Documents/SSL/your_domain.ca-bundle
8.  sudo a2ensite yoursite.com.secured.conf
To activate this virtual host
Besides your secured virtual host, you must have your regular virtual host with 80 port and without SSLEngine on etc. 

9. Change your Laravel .htaccess text to text below, so it will redirect all regular http request to https
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^(yourdomain.com)
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI}%{QUERY_STRING} [L,R]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
10. sudo service apache2 restart :)

Thank you.
Here's an example: https://andymarrel.eu
        

Saturday, May 24, 2014

Github switch between branches after cloning repo

git clone <somerepo> .
git branch -a // View all branches
git checkout -b <branch_name> origin/<branch_name>

Sunday, March 23, 2014

LAMP: Updating PHP from 5.3.x-ubuntu to 5.4.x (custom rep.)

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:ondrej/php5-oldstable
sudo apt-get update; sudo apt-get install php5

Thanks to: http://askubuntu.com/questions/343560/update-server-php-version-to-5-4-10-via-the-command-line

Wednesday, March 19, 2014

CSS #1

CSS position:
Absolute positioning

HTML:
<div class="container">
<div class="innter-container">
</div>
</div>

CSS:
.container { position: relative; }
.inner-container { position: absolute }


CSS after and clearfix:
// This will add 'Sample text' after each p element
//  It also can be p:after, but :: is a CSS 3 syntax
p::after {
content: 'Sample text';
}

// Fixing parent container height, when using inner elements with float:right/left
.container::after {
content: '.';
display: block;
height: 0;
clear: both;
}

CSS Triangle:
width: 0;
height: 0;
border-top: 10px solid #000;
border-left: 10px solid transparent;
border-right: 10px solid transparent;

CSS background:
background-image: url(path_to_img), url(path_to_2_img);
background-repeat: no-repeat, repeat;


Monday, March 17, 2014

Ежедневные достижения

Считаю, что любой человек должен постоянно совершенствоваться. Никогда не поздо начать, правда?  Я упустил много возможностий, совершил кучу ошибок, которые так или иначе повлияли на мою жизнь. Чёрная полоса, затем белая, затем снова чёрная и так всегда. Сначала ты создаешь себя, идешь за своими мечтами, а потом всё сжигаешь и встаёшь на путь саморазрушения.
Однажды я прочитал (а может мне рассказали, или я вообще это сам себе придумал) про человека, который ежедневно записывал свои достижения. Под достижениями он имел в виду не глобальные события, а совсем, с первого взгляда, незначительные вещи (такие как сходил на прогулку, прочитал статью и т.д.), т.е. абсолютно всё, благодаря чему можно стать немного лучше. Именно этим я и планирую заняться. Полагаю, что это хороший способ мотивировать себя. Ну а если не выйдет, я по крайней мере попробовал :)

Достижения за сегодня:
1. Сделал несколько упражнений на лингуалео, начал изучать новые английские слова.
2. Занимался веб-разработкой (делал каркас нового сайта). Скриншот можно посмотреть ниже.










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

Tuesday, March 4, 2014

Laravel custom application autoloading folder

1. Creating folder in your /app/YOUR_DIRECTORY_NAME
2. Adding this directory to array in /app/start/global.php 
ClassLoader::addDirectories(array(
   app_path().'/commands',
   app_path().'/controllers',
   app_path().'/models',
   app_path().'/database/seeds',
   app_path().'/YOUR_DIRECTORY_NAME',
));
3. Now you can add new classes to your /app/YOUR_DIRECTORY_NAME without any namespace (if this class is not in subfolder)

Thursday, January 9, 2014

Мэтью Арнольд "Доверья океан..."

Доверья океан
Когда-то полон был и, брег земли обвив,
Как пояс радужный, в спокойствии лежал
Но нынче слышу я
Лишь долгий грустный стон да ропщущий отлив
Гонимый сквозь туман
Порывом бурь, разбитый о края
Житейских голых скал.

Дозволь нам, о любовь,
Друг другу верным быть. Ведь этот мир, что рос
Пред нами, как страна исполнившихся грез,-
Так многолик, прекрасен он и нов,-
Не знает, в сущности, ни света, ни страстей,
Ни мира, ни тепла, ни чувств, ни состраданья,
И в нем мы бродим, как по полю брани,
Хранящему следы смятенья, бегств, смертей,
Где полчища слепцов сошлись в борьбе своей