Home > Software design >  Writing dynamic Redirect rule in Windows server web.config file
Writing dynamic Redirect rule in Windows server web.config file

Time:04-28

I am facing the problem of SEO canonical issues which I am trying to solve with web.config file. The same page is accessed on multiple URLs (2 specifically)

My server is Windows-based but I am using PHP Codeigniter script.

my URL structure is

https://example.com/xyz/index.php/dynamic-part/optional-dynamic-part

BUT it is also accessible using

example.com/xyz/dynamic-part/optional-dynamic-part

What I want is

  1. The only accessible link should be example.com/xyz/index.php/dynamic-part/optional-dynamic-part
  2. if someone tries to access https://example.com/xyz/dynamic-part/optional-dynamic-part this way, he should be permanently redirected to https://example.com/xyz/index.php/dynamic-part/optional-dynamic-part

I have tried the following:

<rule name="redirecting" patternSyntax="Wildcard">
            <match url="^ci/actionone*"/>
                <conditions>
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
                </conditions>
            <action type="Redirect" url="ci/index.php/{R:1}" redirectType="Permanent" />
        </rule>

Another attempt was:

<rule name="someRule" stopProcessing="true">
<match pattern="^ci" />
<<conditions>
    <add input="{REQUEST_URI}" negate="true" type="Pattern" pattern="^index">
</<conditions>
<action type="Redirect" url="example.com/ci/index.php/actionone" redirectType="Permanent" />
</rule>

<rewriteMaps>
    <rewriteMap name="StaticRedirects">
        <add key="/ci/actionone" value="/ci/index.php/actionone" />
        
    </rewriteMap>
</rewriteMaps>  

Please guide me how to fix this. Thank you

CodePudding user response:

Back again! with a solution that works for me

Here is the solution.

Basically what I did is check if the URL hits with a specific string in my case ci/actionone and have ANY string the URL will be redirected to the action URL.

<rule name="name1: with pagination">
    <match url="^(ci/actionone)/(.*)$"/>
    <action type="Redirect" url="ci/index.php/actionone/{R:2}"/>
</rule>

Similarly, if the URL contains an exact string, it will redirect to the exact action URL

This is because the first page is accessed without pagination and the next page has a pagination slug in the URL.

<rule name="name2: without pagination">
    <match url="^(ci/actionone)$"/>
    <action type="Redirect" url="ci/index.php/actionone"/>
</rule>
  • Related