HTTP to HTTPS redirects on IIS 7.x and higher



This is the most common requirement on most of the Exchange servers hosted on IIS. The server admins configure an http to https redirect.
Today I will be discussing few ways of doing this. I will keep updating this document as I find more ways to do so. I am considering OWA as a sub application under IIS for all the below examples. Here is the structuring of the Web Site:
In this case, we want all the requests (both HTTP & HTTPS) to be redirected on HTTPS to the application called “OWA” under the Default Web Site.

Method 1: Using IIS URL Rewrite Module

For this you will have to install the URL Rewrite module. (FYI, this is available for IIS 7 and higher only.)
Once installed, the URL Rewrite module would be listed under IIS section. There are few articles out there on this. Here are few to list:
  1. http://www.sslshopper.com/iis7-redirect-http-to-https.html
  2. http://www.jppinto.com/2010/03/automatically-redirect-http-requests-to-https-on-iis7-using-url-rewrite-2-0/
These articles are definitely a great repository, however I observed that they have not addressed an important factor.
As specified in the above links add the below section in the web.config at the root of the site:
xml
version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="HTTP/S to HTTPS Redirect" enabled="true" stopProcessing="true"> <match url="(.*)" /> <conditions logicalGrouping="MatchAny"> <add input="{SERVER_PORT_SECURE}" pattern="^0$" /> </conditions> <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
In the above rule I’m checking whether the server variable “SERVER_PORT_SECURE” is set to 1 or 0. (I’m doing a permanent redirect in the above URL, it can be changed accordingly as per the requirement)
If you want to include the query string in the re-written url, then you can add appendQueryString=”true” under the action section.
You can find the complete list of IIS Server variables here: http://msdn.microsoft.com/en-us/library/ms524602(v=vs.90).aspx
SERVER_PORT_SECUREA string that contains either 0 or 1. If the request is being handled on the secure port, then this is 1. Otherwise, it is 0.
Alternatively, instead of the above server variable the following server variable “HTTPS” and “SERVER_PORT” can also be used correspondingly.

NOTE: Ensure the rewrite rule is disabled at each of the virtual directories/applications under the Default Web Site. Due to inheritance, the rule will cause the requests to end up in infinite loop calling itself repeatedly.

Method 2: Using IIS Default Document (a default.asp page)

In this method we will introduce a sample asp page at the root of the website and then add the following piece of code:
<%
If Request.ServerVariables("HTTPS") = "off" Then
Response.Redirect "https://" & Request.ServerVariables("HTTP_HOST") & Request.ServerVariables("UNENCODED_URL")
ElseIf Request.ServerVariables("HTTPS") = "on" Then
Response.Redirect "https://" & Request.ServerVariables("HTTP_HOST") & Request.ServerVariables("UNENCODED_URL")
End If
%>
view rawhttpsRedirect.vb hosted with ❤ by GitHub

Alternatively you could use the port numbers in the above code to achieve the same (ensure to change the port numbers as per the website configuration).

Method 3: Using IIS HTTP Redirect Module

This is one of the simplest methods, but has a lot of limitations and ideally not used. Here is how we do it:
PRE-REQUISITES: HTTP Redirect module is installed and the website has a valid HTTPS binding in place.
  • Launch the IIS Manager.
  • Go to the HTTP Redirect module.
  • Fill the details as per the requirement as shown below:
This may not be ideal for all the scenarios as the user is redirected to a specified URL.

NOTE: Ensure the enforced redirection is removed from each of the virtual directories/applications under the Default Web Site. Due to inheritance, the requests will end up in an endless loop, redirecting to itself repeatedly.
Also ensure Require SSL is not checked at the Root of the website under SSL Settings, this may cause to throw an error page to the users when the browse the site over HTTP. It can be enforced at the application level.
There is another way using custom error pages which has been documented here:
The author in the 2nd link claims that it doesn’t work on IIS 7.5 and higher versions due to updates in the configuration security.
I haven’t found the time to test and write it up and neither am I sure if the above actually works. Once I have tested I will add it up here.


Reference
https://blogs.msdn.microsoft.com/kaushal/2013/05/22/http-to-https-redirects-on-iis-7-x-and-higher/

Import PFX File - Internet Information Server 7

PFX Files & Windows Internet Information Service 7 (IIS)

A PKCS12 (PFX) file is a specially formatted file which includes the SSL Certificate, Private Key and optionally any required Intermediate CA Certificates. The file has an extension of .PFX and is compatible with Windows Internet Information Service (IIS).
To create the PKCS12 (PFX) file please visit the SSL Tools section of our website. Scroll down to the "Convert PEM Formatted File To PKCS12 (PFX Format)" link. You will be required to enter a password for the file - this ensures the security of the file.
If your CSR wasn't generated during the ordering process you can still use our SSL Tools to create a PKCS12 (PFX) file. However, you will be required to provide your associated Private Key when generating the PKCS12 (PFX) file for it to be created successfully.
The PKCS12 (PFX) file will be compressed and saved as a ZIP file, please ensure to UNZIP it before import. The (PKCS12) PFX file should include all required components (SSL Certificate, Private Key and any required Intermediate CA Certificates).

How To Import The PKCS12 (PFX) File Into Microsoft IIS 7

Importing a (PKCS12) PFX file into Microsoft IIS is generally a straight-forward process. Please review the instructions below or follow the instructions that are provided by Microsoft, refer to your server documentation or contact your server vendor.
Step 1 : Click "Start" and choose "Run".
Step 2 : In the "Run" dialogue box type "MMC" and click "OK". The MMC should then appear.
Step 3 : Go to the File tab or menu and select "Add / Remove Snap-In".
Step 4 : Click on "Certificates" and click "Add".
Step 5 : Select "Computer Account" and click "Next".
Step 6 : Select "Local Computer" and click "Finish".
Step 7 : Click "OK" to close the "Add / Remove Snap-In" window.
Step 8 : Double click on "Certificates (Local Computer)" in the center window.
Step 9 : Right click on the "Personal Certificates Store" folder.
Step 10 : Choose "ALL TASKS" then select "Import".
Step 11 : Follow the "Certificate Import Wizard" to import your "Primary Certificate" from the .PFX file.
Step 12 : Browse to the .PFX and enter the associated password when prompted.
Step 13 : If desired, check the box to "Mark This Key As Exportable". We recommend choosing this option.
Step 14 : When prompted, choose to automatically place the Certificates in the Certificate Stores based on the type of the Certificate.
Step 15 : Click "Finish" to close the Certificate Import Wizard.
Step 16 : Close the MMC console. It is not necessary to save any changes that you have made to the MMC console.
The SSL Certificate, Private Key and any Intermediate Certificates should now be imported into your server. You must now follow the instructions below to bind your SSL Certificate to your website profile.

How To Bind An SSL Certificate In Microsoft IIS 7

Once the SSL Certificate has been imported it is important to now bind the SSL Certificate to your website so that the website functions correctly. Your SSL Certificate will not function until the following steps are completed.
Step 1 : Click "Start", "Administrative Tools" and then choose Internet Information Services (IIS) Manager.
Step 2 : Click on the server name and expand the "Sites" folder.
Step 3 : Locate your website (usually this will be called "Default Web Site") and click on it.
Step 4 : From the "Actions" menu (on the right) click on "Site Bindings" or similar.
Step 5. In the "Site Bindings" window, click "Add" or similar. This will open the "Add Site Binding" window.
Step 6 : Under "Type" choose https. The IP address should be the corresponding dedicated IP address of the site or "All Unassigned". The "Port" which traffic will be secured by SSL is usually 443. The "SSL Certificate" field should specify the SSL Certificate that was installed during the import process above.
Step 7 : Click "OK".
Step 8 : Your SSL Certificate should now be installed and functioning correctly in conjunction with your website. Occasionally a restart of IIS may be required before the new SSL Certificate is recognized.

PhpMyAdmin - Basic Administration

Nginx

Option 1: subdomain

Using this method, you'll access PhpMyAdmin as phpmyadmin..
Configurating Nginx is similar to Apache (and Lighttpd, for that matter). Make sure Nginx is setup to serve PHP files (see Nginx).
You can setup a sub domain (or domain) with a server block like so (if using php-fpm):
 server {
         server_name     phpmyadmin.;
 
         root    /usr/share/webapps/phpMyAdmin;
         index   index.php;
 
         location ~ \.php$ {
                 try_files      $uri =404;
                 fastcgi_pass   unix:/run/php-fpm/php-fpm.sock;
                 fastcgi_index  index.php;
                 include        fastcgi.conf;
         }
 }
To access this url on your localhost, you can simply add an entry in /etc/hosts:
 127.0.0.1 phpmyadmin.
You need to update PHP's open_basedir option to add the appropriate directories. Either in /etc/php/php.ini:
 open_basedir = /srv/http/:/home/:/tmp/:/usr/share/pear/:/usr/share/webapps/:/etc/webapps/
Or if running php-fpm with a separate entry for phpmyadmin, you can overwrite this value in your pool definition (in /etc/php/fpm.d/):
 php_admin_value[open_basedir] = /tmp/:/usr/share/webapps/:/etc/webapps/
If the above doesn't fix it try adding the following to your NGINX Configuration below the other fastcgi_param (I think its something to do with the Suhosin-Patch)
 fastcgi_param  PHP_ADMIN_VALUE  open_basedir="/srv/http/:/home/:/tmp/:/usr/share/pear/:/usr/share/webapps/:/etc/webapps/";
While you can enter anything for the blowfish password, you may want to choose a randomly generated string of characters (most likely for security reasons). Here's a handy tool that will do that for you on the web[2].
When using SSL, you might run into the problem that the links on the pages generated by phpMyAdmin incorrectly start with "http" instead of "https" which may cause errors. To fix this, you can add the following fcgi_param to your SSL-enabled server section (in addition to your usual fastcgi params):
 fastcgi_param HTTPS on;

Option 2: subdirectory using symlink

Using this method, you'll access PhpMyAdmin as localhost/phpmyadmin, similarly to Apache.
To get PhpMyAdmin working with your nginx setup, first take note of the root of the server you want to use. Supposing it is /srv/http, now create a symlink:
 # ln -s /usr/share/webapps/phpMyAdmin/ /srv/http/phpmyadmin

Option 3: subdirectory using alias

If for some reason you are unable to create a symlink in the root of the server or would just rather use an alias, you can use this example configuration.
Using this method, you'll access PhpMyAdmin as localhost/phpmyadmin, similarly to Apache.
 location /phpmyadmin {
         alias /usr/share/webapps/phpMyAdmin;
         # Optionally set separate access and error logs for phpMyAdmin
         access_log /var/log/nginx/phpmyadmin_access.log;
         error_log /var/log/nginx/phpmyadmin_error.log;
         index   index.php;  
         try_files $uri $uri/=404;
         # Deny some static files
         location ~ ^/phpmyadmin/(README|LICENSE|ChangeLog|DCO)$ {
                 deny all;
         }
         # Deny .md files
         location ~ ^/phpmyadmin/(.+\.md)$ {
                 deny all;
         }
         # Deny some directories
         location ~ ^/phpmyadmin/(doc|sql|setup)/ {
                 deny all;
         }
         #FastCGI config for PhpMyAdmin
         location ~ /phpmyadmin/(.+\.php)$ {
                 fastcgi_param  SCRIPT_FILENAME /usr/share/webapps/phpMyAdmin/$1;
                 fastcgi_pass   unix:/run/php-fpm/php-fpm.sock;
                 fastcgi_index  index.php;
                 include        fastcgi.conf;
         }
 }

phpMyAdmin configuration

phpMyAdmin's configuration file is located at /etc/webapps/phpmyadmin/config.inc.php. If you have a local MySQL server, it should be usable without making any modifications.
If your MySQL server is not on the localhost, uncomment and edit the following line:
$cfg['Servers'][$i]['host'] = 'localhost';
If you would like to use phpMyAdmin setup script by calling http://localhost/phpmyadmin/setup you will need to create a config directory that's writeable by the httpd user in /usr/share/webapps/phpMyAdmin as follows:
# cd /usr/share/webapps/phpMyAdmin
# mkdir config
# chgrp http config
# chmod g+w config

Add blowfish_secret passphrase

If you see the following error message at the bottom of the page when you first log in to /phpmyadmin (using a previously setup MySQL username and password) :
ERROR: The configuration file now needs a secret passphrase (blowfish_secret)
You need to add a unique password for the blowfish algorithm (which is used by phpMyAdmin to secure the authentication procedure) between the following ''. You can use any password generator for that matter, a key length of 32 is recommended.
/etc/webapps/phpmyadmin/config.inc.php
$cfg['blowfish_secret'] = ''; /* YOU MUST FILL IN THIS FOR COOKIE AUTH! */
The error should go away if you refresh the phpmyadmin page.

Enabling Configuration Storage (optional)

Now that the basic database server has been setup, it is functional, however by default, extra options such as table linking, change tracking, PDF creation, and bookmarking queries are disabled. You will see a message at the bottom of the main phpMyAdmin page, "The phpMyAdmin configuration storage is not completely configured, some extended features have been deactivated. To find out why...", This section addresses how to to enable these extra features.
Note: This example assumes you want to use the username pma as the controluser, and pmapass as the controlpass. These should be changed (the very least, you should change the password!) to something more secure.
In /etc/webapps/phpmyadmin/config.inc.php, uncomment (remove the leading "//"s on) these two lines, and change them to your desired credentials:
// $cfg['Servers'][$i]['controluser'] = 'pma';
// $cfg['Servers'][$i]['controlpass'] = 'pmapass';
You will need this information later, so keep it in mind.
Beneath the controluser setup section, uncomment these lines:
/* Storage database and tables */
// $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
// $cfg['Servers'][$i]['bookmarktable'] = 'pma__bookmark';
// $cfg['Servers'][$i]['relation'] = 'pma__relation';
// $cfg['Servers'][$i]['table_info'] = 'pma__table_info';
// $cfg['Servers'][$i]['table_coords'] = 'pma__table_coords';
// $cfg['Servers'][$i]['pdf_pages'] = 'pma__pdf_pages';
// $cfg['Servers'][$i]['column_info'] = 'pma__column_info';
// $cfg['Servers'][$i]['history'] = 'pma__history';
// $cfg['Servers'][$i]['table_uiprefs'] = 'pma__table_uiprefs';
// $cfg['Servers'][$i]['tracking'] = 'pma__tracking';
// $cfg['Servers'][$i]['userconfig'] = 'pma__userconfig';
// $cfg['Servers'][$i]['recent'] = 'pma__recent';
// $cfg['Servers'][$i]['favorite'] = 'pma__favorite';
// $cfg['Servers'][$i]['users'] = 'pma__users';
// $cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
// $cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
// $cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
// $cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
// $cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
// $cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
Next, create the user with the above details. Don't set any permissions for it just yet.
Note: If you can't login to phpmyadmin, make sure that your mysql server is started.
creating phpMyAdmin database
Using the phpMyAdmin web interface: Import /usr/share/webapps/phpMyAdmin/sql/create_tables.sql from phpMyAdmin -> Import. or Using command line: mysql -u root -p < /usr/share/webapps/phpMyAdmin/sql/create_tables.sql.
creating phpMyAdmin database user
Now to apply the permissions to your controluser, in the SQL tab, make sure to replace all instances of 'pma' and 'pmapass' to the values set in config.inc.php. If you are setting this up for a remote database, then you must also change 'localhost' to the proper host:
GRANT USAGE ON mysql.* TO 'pma'@'localhost' IDENTIFIED BY 'pmapass';
GRANT SELECT (
    Host, User, Select_priv, Insert_priv, Update_priv, Delete_priv,
    Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv,
    File_priv, Grant_priv, References_priv, Index_priv, Alter_priv,
    Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv,
    Execute_priv, Repl_slave_priv, Repl_client_priv
    ) ON mysql.user TO 'pma'@'localhost';
GRANT SELECT ON mysql.db TO 'pma'@'localhost';
GRANT SELECT ON mysql.host TO 'pma'@'localhost';
GRANT SELECT (Host, Db, User, Table_name, Table_priv, Column_priv)
    ON mysql.tables_priv TO 'pma'@'localhost';
In order to take advantage of the bookmark and relation features, you will also need to give pma some additional permissions:
Note: as long as you did not change the value of $cfg['Servers'][$i]['pmadb'] in /etc/webapps/phpmyadmin/config.inc.php, then  should be phpmyadmin
GRANT SELECT, INSERT, UPDATE, DELETE ON .* TO 'pma'@'localhost';
Log out, and back in to ensure the new features are activated. The message at the bottom of the main screen should now be gone.

Accessing your phpMyAdmin installation

Your phpMyAdmin installation is now complete. Before you start using it you need to restart Apache.
You can access your phpMyAdmin installation by going to http://localhost/phpmyadmin/

Troubleshooting

Fixing open_basedir warning

If you see the following Warning when entering the homepage of PhpMyAdmin:
Warning in ./libraries/Config.class.php#1147
file_exists(): open_basedir restriction in effect. File(./config.inc.php) is not within the allowed path(s): (/srv/http/:/home/:/tmp/:/usr/share/pear/:/usr/share/webapps/)
It means that phpmyadmin was not able to find where the config.inc.php file is located.
In order to fix that, you need to indicate the path in /etc/php/php.ini of the phpmyadmin directory containing the file, which should be /etc/webapps, putting it at the end of the paths separated with a :in the open_basedir variable:
/etc/php/php.ini
open_basedir = /srv/http/:/home/:/tmp/:/usr/share/pear/:/usr/share/webapps/:/etc/webapps/
Once you have done that, restart httpd.service.
Now refresh the page, and you should no longer have the warning.

#2006 - MySQL server has gone away

If, when trying to log into PhpMyAdmin, you encounter
#2006 - MySQL server has gone away

Connection for controluser as defined in your configuration failed.
a fix seems to be to make sure you do not have SSL connection between PhpMyAdmin and MariaDB activated. Hence comment out or set to false the following line:
/etc/webapps/phpmyadmin/config.inc.php
$cfg['Servers'][$i]['ssl'] = true;