How to recompile a package with flags?

Well, you said you run

nix-env -iA nixpkgs.openssl

but the log says you run

nix-env -iA nixpkgs.openssl_1_1

These are different things. You should create overrides in overlays for openssl_1_1 as well.

I want to use this function.
What file do I put it in?

You can put it into overlay! It will look like:

self: super: {
  optimizeWithFlags = pkg: flags:
    pkg.overrideAttrs (old: {
      NIX_CFLAGS_COMPILE = [ (old.NIX_CFLAGS_COMPILE or "") ] ++ flags;
    });

  optimizeForThisHost = pkg:
    self.optimizeWithFlags pkg [ "-O3" "-march=native" "-fPIC" ];

  openssl = self.optimizeForThisHost super.openssl;
}

I’ve modernized the optimizeWithFlags function a bit. I’ve also tested this in Docker nixos/nix. See also nixpkgs/pkgs/stdenv/adapters.nix at 47b551c6a854a049045455f8ab1b8750e7b00625 · NixOS/nixpkgs · GitHub

The utils method is much more complicated compared to this. They create a custom file with functions, utils.nix, which looks like:

pkgs: rec {
  optimizeWithFlags = ,,,;

  optimizeForThisHost = pkg:
    optimizeWithFlags pkg [ "-O3" "-march=native" "-fPIC" ];

  withDebuggingCompiled = pkg:
    optimizeWithFlags pkg [ "-DDEBUG" ];
}

and do the overrides in config.nix (NOT in overlay), in packageOverrides attribute. And yes, there is utils = import ./utils.nix; somewhere in the code, but if you use the mine overlay, it is no longer needed.