开发者

URL Redirection without the filename in ColdFusion?

开发者 https://www.devze.com 2023-02-18 11:54 出处:网络
I\'m trying to achieve 301 redirects such that开发者_JAVA百科 all of my URLs are redirected to the www version of the given page. Our page structure is: url.com/home/default.cfm. I am trying to rewrit

I'm trying to achieve 301 redirects such that开发者_JAVA百科 all of my URLs are redirected to the www version of the given page. Our page structure is: url.com/home/default.cfm. I am trying to rewrite the URLs in ColdFusion to the current directory without the filename.

The code I am using is this:

<cfif (CGI.SERVER_NAME NEQ "www.url.com")>
<!-- Save the URL (and $_GET variables too) as the string 'strUrl' -->
<!-- <cfset strUrl = CGI.script_name & "?" & CGI.query_string />-->
<cfset strUrl = CGI.script_name />
<!-- Use 301 for SEO-friendly redirects -->
<cfheader statuscode="301" statustext="Moved permanently">
<!-- Redirect to new website (this case, added www.) with strUrl added on -->
<cfheader name="Location" value="http://www.url.com#strUrl#">
</cfif>

This is so close, except CGI.script_name returns the path WITH the filename. Any ideas how to get just the directory? Keep in mind we may have nested directories, e.g., /foo1/foo2/.

Thanks.


If your intention is to redirect all traffic going to "domain.com" to "www.domain.com", you may be better off doing it at the webserver level. The webserver will take care of not just CF files, but also static resources like images, css & js files, etc.


You can use getDirectoryFromPath() to do this, which will also preserve the trailing slash.

<cfset strUrl = getDirectoryFromPath(cgi.SCRIPT_NAME)>

In addition you simplify the code by using the cflocation tag and specifying the statusCode attribute.

<cfif (CGI.SERVER_NAME NEQ "www.url.com")>
<!-- Save the URL (and $_GET variables too) as the string 'strUrl' -->
<!-- <cfset strUrl = CGI.script_name & "?" & CGI.query_string />-->
<cfset strUrl = getDirectoryFromPath(CGI.script_name) />
<!-- Use 301 for SEO-friendly redirects -->
<cflocation url="http://www.url.com#strUrl#" statusCode="301">
</cfif>


Try this

<cfset strUrl = listDeleteAt(cgi.SCRIPT_NAME,listLen(cgi.SCRIPT_NAME,'/'),'/') />


Or try this

<cfset strUrl = Replace(cgi.SCRIPT_NAME, ListLast(cgi.SCRIPT_NAME,'/'), '')>

to have the trailing slash as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号