Search code examples
coldfusionhttp-status-code-301

Is this the best place to use a 301 redirect to control which domain name is used?


I am using ColdFusion 9.0.1

I have a new site that is accessible through a few domains such as:

mydomain.com
www.mydomain.com
foo.mydomain.com

For SEO and tracking purposes, I want to make sure that only "mydomain.com" is indexed and accessed. So, every request that tries to access my site through other domains will be 301 directed to "mydomain.com".

I want to make sure that I capture and preserve the query string so that I don't just send people to the home page.

I will also make sure that I can access the site locally at 127.0.0.1

I wondering where in the code is the best place to do this SPECIFIC type of redirect. My guess it's in application.cfc near the top, in the onRequestStart() method.

Is this best place to put the code and does is this code complete? Is there a better way to code this?

<cfscript>
ThisHost = CGI.HTTP_HOST;
QString = CGI.QUERY_STRING;
GoToURL = "http://mydomain.com?" & QString;
if (ThisHost != "mydomain.com" && ThisHost != "127.0.0.1") {
    writeOutput("<cfheader statuscode='301' statustext='Moved permanently'>");
    writeOutput("<cfheader name='location' value='#GoToURL#'>");
    abort;
}
</cfscript>

UPDATE

I know this isn't the best way to accomplish what I need, because this task is much better suited to the web server's skill set. Here's my code till I can implement this on the web server:

<cfscript
ThisHost = CGI.HTTP_HOST;
QString = CGI.QUERY_STRING;
GoToURL = "http://flyingpiston.com/?" & QString;
if (ThisHost != "flyingpiston.com" && ThisHost != "127.0.0.1:8500") {
    location(GoToURL, false, 301);  
}
<cfscript

Solution

  • I agree with other comments and answers that doing this at the web server is a better solution. I would also point out that if you want to use the script syntax, this is entirely wrong and will simply return a string to the browser:

    writeOutput("<cfheader name='location' value='#GoToURL#'>");
    

    In ColdFusion 9, you would instead use the location() function:

    location("url", addtoken, statusCode);
    

    In your case:

    location(GoToURL, false, 301);
    

    Your GoToURL variable is also missing the page name, so you'd need to add CGI.SCRIPT_NAME into the mix just before the ? to get the full URL being called.

    With the tag syntax (as of ColdFusion 8 I believe), there is no need to use the CFHEADER tag for a 301 redirect. The CFLOCATION tag now supports a statuscode attribute which can be set to 301 as needed.