Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Website web.config > Is it possible to redirect an incorrect subdomain to a certain page?

Is it possible to redirect an incorrect subdomain (A non-existant subdomain) to a certain page (Custom error page)?

EDIT: Using a web.config file

For example, if I typed http://foo.squishling.co.uk/ it would redirect to something like http://squishling.co.uk/errors/incorrect_subdomain.html/, as http://foo.squishling.co.uk/ isn't a correct subdomain.

I haven't seen any code that does this, so is it possible?
EDIT: If it isn't possible, please say so

Thanks in advance, ~ Squishling

EDIT: If this is possible, a possible way of doing it would be when the server recieves a request for the incorrect subdomain, just trick the request into requesting an error page

like image 568
Zoe Avatar asked Oct 30 '22 03:10

Zoe


1 Answers

Yes, it's possible. Here's how with IIS 10 + UrlRewrite 2.1.

For example's purposes let's assume I have:

  • A valid domain/port good.localhost:81
  • my custom error file @ /error.txt

Step 1: Set up site bindings to accept requests for sub domains

IIS manager -> web site context menu -> "Edit Bindings.." Edit accepted host name to accept *.<yourDomain>. For the example case: enter image description here

Detailed steps can be found from documentation page "Wildcard Host Header Support".

Now site should respond to both http://good.localhost:81 as well as http://bad.localhost:81.

Step2: install Url rewrite module

You can find URL rewrite module installer from here: https://www.iis.net/downloads/microsoft/url-rewrite

Step3: configure redirect rule

While you could use IIS MAnager's GUI for this, you could as well just handwrite something like this to your web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
        <rules>
            <rule name="DirectBadSubdomainsRule" stopProcessing="true">
                <match url=".*" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^good\.localhost:81" negate="true" />
                    </conditions>
                    <action type="Redirect" url="http://good.localhost:81/error.txt" redirectType="Temporary" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

You can use the power of regex to determine which subdomains are valid and which ones are not. Also you can decide exactly which redirection code you want. The example above uses Temporary redirect (HTTP307).

There's a lot of documentation in here: https://www.iis.net/downloads/microsoft/url-rewrite

Testing

Non-good domain should now return redirection response:

  1. http://bad.localhost:81/correct.txt -> HTTP307
  2. http://good.localhost:81/error.txt -> HTTP200
like image 181
Imre Pühvel Avatar answered Jan 02 '23 21:01

Imre Pühvel