skip to Main Content

I’m trying to redirect with nginx all urls with the subdomain "admin" to www, except for the ones containing "wp-admin".

The behavior should be the following:

https://admin.domainname.com/slug => https://www.domainname.com/slug

https://admin.domainname.com/wp-admin/slug => no redirect

I tried the following one but it’s not working:

rewrite ^(?!/[^/]+/wp-admin/)(/.*)admin(?.*)?$ $1www$2 permanent;

I guess the (/.*)admin(?.*) part is not correct. How can I capture the "admin" subdomain?

Thanks for your help.

3

Answers


  1. Chosen as BEST ANSWER

    Here is the solution that worked:

    if ($uri !~ "^/(wp-admin|wp-login.php)(.*)"){
      return 301 https://www.domainname.com$request_uri;
    }
    

  2. This answers only the regex part of the question.

    The @IvanShatsky’s answer is more useful as it addresses the the main issue of the OP


    Not sure about your exact requirements, but here is a quick fix:

    const rewrite = (url) => {
      const new_url = url.replace(/^(https|http)://admin.((.(?!/wp-admin/))*)$/, '$1://www.$2')
      console.log(new_url)
    }
    rewrite('https://admin.domainname.com/slug')
    rewrite('https://admin.domainname.com/wp-admin/slug')
    1. (https|http) – gets protocol
    2. ://admin. – check if there is ://admin.
    3. ((.(?!/wp-admin/))*) – gets every char until the end, if it is not followed by /wp-admin/, fails otherwise.
    Login or Signup to reply.
  3. You can’t check domain name with the rewrite directive, it works with so-called normalized URI (in your examples it will be /slug or /wp-admin/slug). What you can do is to check Host HTTP header value:

    if ($http_host = 'admin.domainname.com') {
        rewrite ^(?!/wp-admin)(.*)$ https://www.domainname.com$1 permanent;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search